I've been trying to set up a redirect for my website from www.example.com to example.com using Nginx, but it's not working as expected. Even after setting up the redirect, accessing www.example.com does not redirect me to example.com, it remains on www.example.com.
Here is my current Nginx configuration:
server {
server_name www.example.com example.com;
root /var/www/examplecom;
index index.php ;
location ~ \.(gif|jpg|png)$ {
add_header Vary "Accept-Encoding";
add_header Cache-Control "public, no-transform, max-age=31536000";
}
location ~* \.(css|js)$ {
add_header Cache-Control "public, max-age=604800";
log_not_found off;
access_log off;
}
location ~*.(mp4|ogg|ogv|svg|svgz|eot)$ {
add_header Cache-Control "max-age=31536000";
access_log off;
}
charset utf-8;
server_tokens off;
client_max_body_size 100M;
location / {
try_files $uri $uri/ =404;
}
location ~ /\.ht {
deny all;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
listen [::]:443 ssl; # managed by Certbot
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 = example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name www.example.com example.com;
return 404; # managed by Certbot
}
I initially configured the Nginx server block to redirect all requests from www.example.com to example.com. I expected that when accessing www.example.com, the browser would be automatically redirected to example.com, effectively removing the 'www' from the URL.
In my Nginx configuration, I set up a rule to perform a 301 redirect from www.example.com to example.com. This was done for both HTTP and HTTPS requests, ensuring that regardless of the protocol used, the user would always be redirected to the 'www'-free version of the site.
Any help would be appreciated. Thanks in advance.