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, but will cause a 404 error

I have A records setup for both the and pointing to the same IP address

Ideally I would like to redirect all traffic to

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/;

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

	index index.php index.html;
	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/; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/; # 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 = {
        return 301$request_uri;
    } # managed by Certbot

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

    listen 80;
    return 404; # managed by Certbot

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


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

    return       301$request_uri;

In your second server block change




Kind regards, KDSys