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, if

Stops 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

Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus


The fastest way to redirect traffic from www to non-www domain in nginx

Clutter-free software concepts.
Translations English Español

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

·