9

How can I redirect "http://domain.com." to "http://domain.com" with Nginx?

What's the recommended way of doing this? Regex or is there any other options?

1

2 Answers 2

22

The following snippet does this in a general way, without having to hard code any hostnames (useful if your server config handles requests for multiple domains). Add this inside any server definition that you need to.

if ($http_host ~ "\.$" ){
    rewrite ^(.*) $scheme://$host$1 permanent;
}

This takes advantage of the fact (pointed out by Igor Sysoev) that $host has the trailing dot removed, while $http_host doesn't; so we can match the dot in $http_host and automatically use $host for the redirect.

4
  • 1
    Use rewrite ^(.*) $scheme://$host$1 permanent; to get rid of hardcoded scheme. Dec 11, 2013 at 15:06
  • Thanks for the suggesion (and edit) @SlavaFominII - much better.
    – El Yobo
    Dec 17, 2013 at 0:26
  • In the 1.10 Nginx, the trailing dot is not in the $host or $http_host.
    – xiaoke
    Jun 22, 2019 at 1:08
  • I did not test Nginx 1.10, but using this excellent answer, I tested 1.18, and $http_host still includes the trailing dot, so this solution should still work. Sep 2, 2021 at 15:17
0

You will need to use Regex.

server {
    listen       80;
    server_name  domain.com.WHATEVER, domain.com.WHATEVER-2, domain.com.WHATEVER-3;
    rewrite  ^  $scheme://domain.com$request_uri?  permanent;
}

From: http://wiki.nginx.org/HttpRewriteModule

redirect - returns temporary redirect with code 302; it is used if the substituting line begins with http:// permanent - returns permanent redirect with code 301

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.