I want www.example.app to go to example.app for SEO, and I followed several tutorials and problem solutions but can’t seem to get it working.
I added a separate server block that redirects to the non-www domain and restarted nginx several times, also accessing my site from an incognito window.
Here is my /etc/nginx/sites-available/default
configuration file.
Any help would be appreciated!
server {
server_name www.example.app;
return 301 $scheme://example.app$request_uri;
}
server {
listen 80;
listen [::]:80;
root /var/www/html/;
index index.php index.html index.htm index.nginx-debian.html;
server_name exampe.app;
location / {
try_files $uri $uri/ =404;
}
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
}
location ~* .(pdf)$ {
expires 30d;
}
location ~ .php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}
location ~ /.ht {
deny all;
}
error_page 404 /customerror_404.html;
location = /customerror_404.html {
root /usr/shar/nginx/html;
internal;
}
}
server {
root /var/www/html/;
index index.php index.html index.htm index.nginx-debian.html;
server_name example.app; # managed by Certbot
location / {
try_files $uri $uri/ =404;
}
location ~ .php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}
location ~ /.ht {
deny all;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.app/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.app/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 = example.app) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80 ;
listen [::]:80 ;
server_name example.app;
return 404; # managed by Certbot
}
2
Answers
I use this to redirect from www domain to non-www domain.
You need to tell nginx if what host you want to redirect from in this case from www.
If this does not work. You may need to set server name to be like this
So the host is recognized.
I am using it in my config: