Nginx redirect subdomain from www to non-www

March 10, 2018 6.2k views
Nginx LEMP PHP PHP Frameworks Ubuntu 16.04

Hello, I'm using this nginx conf:

root /var/www/html/laravel/public;

        index index.php index.html index.htm index.nginx-debian.html;

        server_name *;

        location / {
                try_files $uri $uri/ /index.php?$query_string;

        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php7.1-fpm.sock;

It is multi-tenancy project, I want redirect all subdomains with www to non-www. My question is, how? :) I have one config file for all subdomains.

In my root nginx conf I just used:

server {
    return 301 $scheme://$request_uri;

But in subdomains config I cant use it. My nginx conf skills are not very good, so pls help.

Thank you all

1 comment
  • Not sure what you mean here:

    But in subdomains config I cant use it.

    There is no such thing as "subdomains" conf. Every site (virtual host) should have its own configuration file.

4 Answers
oksim March 20, 2018
Accepted Answer

If someone need this, solution is:

if ($host ~* ^www\.(.*)) {
                set $host_without_www $1;
                rewrite ^(.*) http://$host_without_www$1 permanent;

Hello, thanks.

But I think we did not understand each other :)

What I need is redirect from www subdomain to non www subdomain, not to domain.

So: redirect to redirect to

and NOT: to

But I dont have conf files for each of this subdomains. I have only one sub nginx conf as I mentioned in my first question.

Thank you.

You can target all www.* hostnames by using a regular expression:

server {
    listen 80;
    server_name ~^www\..+\.domain\.com$;
    return 301 $scheme://$request_uri;

Make sure you escape any dots in your domain name by adding a \ before them like in the snippet above.

  • This doesn't seem to work for me. I put it in the default.conf without success.
    We want to redirect like this: redirect to redirect to

redirect 301 subdomain www to non www
RewriteCond %{SERVER_PORT} ^80$

RewriteCond %{HTTPHOST} ^$ [NC]
RewriteRule .? https://%{HTTP

RewriteCond %{HTTPHOST} ^www.([^.]$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST
URI} [R=301,L]

Have another answer? Share your knowledge.