Redirecting to with Nginx not working

I've been trying to set up a redirect for my website from to using Nginx, but it's not working as expected. Even after setting up the redirect, accessing does not redirect me to, it remains on

Here is my current Nginx configuration:

server {
    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/; # 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;
    listen [::]:80;
    return 404; # managed by Certbot

I initially configured the Nginx server block to redirect all requests from to I expected that when accessing, the browser would be automatically redirected to, effectively removing the 'www' from the URL.

In my Nginx configuration, I set up a rule to perform a 301 redirect from to 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.

1 Like

Might be because e.g. Chrome nowadays prefers HTTPS so it wouldn't get to the HTTP server block containing the redirects currently configured.

You might need to include the www to apex domain redirect to the HTTPS block too.


This was really helpful. Thank you!


This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.