Redirect Www to Non Www With Nginx
Published:
Last modified:
Overview
A common need when setting up an Nginx web server, is to redirect
all the traffic from the www to the non-www version. (e.g.:
www.example.com
-> example.com
).
This is a simple approach to do it.
Directives
We define two virtual servers with the server
directive
- one for the non-www version
- another one for the www version that redirects to the
non-www version:
return 301 $scheme://example.com$request_uri;
Syntax: return code [text]; return code URL; return URL; Default: — Context: server, location, ifStops processing and returns the specified code to a client. The non-standard code 444 closes a connection without sending a response header.
In /etc/nginx/sites-available/example.com
:
server {
# ...
server_name example.com;
}
# remove 'www'
server {
# ...
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
Now reload the new configuration:
systemctl reload nginx.service
Test
To test we use cURL
:
$ curl -I https://www.example.com HTTP/2 301 location: http://tablaveloz.com/ ... $ curl -I https://example.com HTTP/2 200 ...
References
- http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#return
- http://nginx.org/en/docs/http/ngx_http_core_module.html#server
- https://www.nginx.com/blog/creating-nginx-rewrite-rules/
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/301
comments powered by Disqus
- Secure Nginx ServerAugust 30, 2018
- Redirect Www to Non Www With Nginx
Articles
Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.
Powered by SimpleIT Hugo Theme
·