Redirect Www to Non Www With Nginx

Last modified:


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.: ->

This is a simple approach to do it.


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://$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/

server {
	# ...

# remove 'www'
server {
	# ...
    return 301 $scheme://$request_uri;

Now reload the new configuration:

systemctl reload nginx.service


To test we use cURL:

$ curl -I
HTTP/2 301
$ curl -I
HTTP/2 200 


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