Question

How do I get Nginx working for www version of my site

  • Posted October 11, 2019
  • Nginx

I have my Laravel app configured on Ubuntu 16.04.6 x64 with nginx and I keep getting a 404 page when you try load the site with the “www” prefix

It all works perfect at https://example.com, but https://www.example.com will cause a 404 error

I have A records setup for both the www.example.com and example.com pointing to the same IP address

Ideally I would like to redirect all https://www.example.com traffic to https://example.com

The nginx conf file is below, would appreciate some help debugging

I’ve tried adding a 301 redirect at the start and end of the file but it doesn’t seem to work

Interestingly I can access static files fine at www, it’s any of the laravel paths that seem to trigger a 404

server {

	root /var/www/example.com/web/public;

	error_log /var/www/example.com/errors.log;
	access_log /var/log/nginx/example.comaccess_log.log; 

	index index.php index.html;
	server_name example.com www.example.com;
	client_max_body_size 80m;

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

	location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
		expires 365d;
	}

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

	location ~ /\.ht {
		deny all;
	}



    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}

server {
    if ($host = www.example.com) {
        return 301 https://example.com$request_uri;
    } # managed by Certbot


    if ($host = hostelpass.co) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


	server_name example.com www.example.com;
    listen 80;
    return 404; # managed by Certbot

}
server {
        server_name www.example.com;
        return 301 $scheme://example.com$request_uri;
}

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Accepted Answer

Hi @rob0a82e551ed787c4c1bf9f4f,

Nginx doesn’t like a lot of different server_names in your server blocks. I have a couple of suggestions. Let’s try one

In your first server block try to do the following

    server_name  www.mydomain.com;
    return       301 http://mydomain.com$request_uri;

In your second server block change

server_name example.com www.example.com;

to

server_name example.com;

Kind regards, KDSys