How to redirect www.example.com
to example.com
?
#2336
-
I already got this code to redirect to pages without trailing slashes. /// A handler that redirects to the no-trailing-slash version
/// of the URL, if the URL ends in a trailing slash.
#[derive(Clone)]
pub struct SlashRemover;
#[rocket::async_trait]
impl Handler for SlashRemover {
async fn handle<'r>(&self, req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r> {
if req.uri().path().ends_with('/') && req.uri().path().to_string().chars().count() > 1 {
println!("{}", req.uri().clone().into_owned().into_normalized());
Outcome::from(
req,
Redirect::to(req.uri().clone().into_owned().into_normalized()),
)
} else {
Outcome::forward(data)
}
}
}
impl From<SlashRemover> for Vec<Route> {
fn from(sr: SlashRemover) -> Vec<Route> {
vec![Route::new(Method::Get, "/<..>", sr)]
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
This is actually fairly simple. First, you need to detect that the client has made a request for However, I'm also curious what the utility of this is. Rocket's default behavior is to ignore the trailing slash, and by default, unless you create specific Fairings to differentiate the various subdomains, Rocket will ignore the subdomain. The only potential issue I could see cropping up is a subdomains might have separate cookies & local storage on the client side. This can be solved for cookies by setting the |
Beta Was this translation helpful? Give feedback.
This is actually fairly simple. First, you need to detect that the client has made a request for
www.ex.com
rather thanex.com
, which can be checked via theHost
header.Request
has a specific method for checking the host (note that if the Host is not sent, you CANNOT identify what domain the user-agent is actually requesting). Then, simply redirect to the correct domain, via the sameRedirect
method. I recommend using theuri!()
macro if possible.However, I'm also curious what the utility of this is. Rocket's default behavior is to ignore the trailing slash, and by default, unless you create specific Fairings to differentiate the various subdomains, Rocket will ignore the subdomain. The…