NGINX redirection with CNAME

cname-recordhttpsnginxredirection

It's my first time using NGINX and I running into some trouble.

So I have a A record pointing to test.example.com and I created a CNAME toto.example.com redirecting to test.example.com
test.example.com is working fine. When I get access to it, I am redirected to test.example.com/mysite (I made a redirection on NGINX).
I also need to mention that my NGINX is redirecting every request in HTTPS (with a Let's Encrypt certificate).

The thing that I want is, when I go to toto.example.com I want it to be redirected to test.example.com/mysite BUT still having the browser showing toto.example.com/mysite instead of having test.example.com/mysite as the URL.

How can I do that please? Find bellow my NGINX config (I only have one site setup). Please, keep in mind that every request must be sent in HTTPS not HTTP.

server {
    listen 80;
    server_name test.example.com;

    include snippets/letsencrypt.conf;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name test.example.com;
    root /var/www;

    ssl_certificate /path/to/my/certificate;
    ssl_certificate_key /path/to/my/key;
    ssl_trusted_certificate /path/to/my/certificate;

    include snippets/ssl.conf;
    include snippets/letsencrypt.conf;

    location / {
       try_files $uri $uri/ /index.php;
       return 301 https://test.example.com/mysite;
    }

    location /sitetwo {
       index index.php;
       try_files $uri $uri/ /sitetwo/index.php;
    }

    location /sitethree{
       proxy_pass http://127.0.0.1:11334/;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location /mysite {
       index index.php;
       try_files $uri $uri/ /mysite/index.php;

    }

    location ~ ^/mysite/(README|INSTALL|LICENSE|CHANGELOG|UPGRADING)$ {
       deny all;
    }

    location ~ ^/mysite/(bin|SQL|config|temp|logs)/ {
       deny all;
    }

    location ~* \.php$ {
         fastcgi_split_path_info ^(.+?\.php)(/.*)$;
         if (!-f $document_root$fastcgi_script_name) {return 404;}
         fastcgi_pass  unix:/run/php/php7.3-fpm.sock;
         fastcgi_index index.php;
         include fastcgi_params;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Best Answer

Problem solved!! I put a / at the end of the return 301 URL. Doing so didn't work. So I removed the / and it worked.

I had that:

return 301 https://toto.example.com/mysite/;

And I did that:

return 301 https://toto.example.com/mysite;

Now everything is working perfectly! Thank you very much Richard!

Related Topic