Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx redirect http to https and remove trailing slashes with one single redirect

I want to redirect http to https and remove trailing slashes in nginx with one single redirect. The solution I have today is the following:

server {
    listen 80;
    server_name www.example.com
    rewrite ^/(.*)/$ /$1 permanent;
    return 301 https://$host$request_uri;
}

The problem with this solution is that it will give two redirects

Gives Two redirects:

http://www.example.com/test/ --> http://www.example.com/test
http://www.example.com/test --> https://www.example.com/test

Is it possible to make a solution where you only get one single redirect like bellow?

http://www.example.com/test/ --> https://www.example.com/test

when I looked through the documentation of nginx rewrite and return methods I felt like it should be possible to do it with a single rewrite somehow:

rewrite ^/(.*)/$ https://$host$request_uri permanent;

But nothing I have tried have given me the correct results.

like image 763
TensaiNiNaru Avatar asked Oct 18 '22 12:10

TensaiNiNaru


1 Answers

You already had the components of a correct solution. Use the scheme and hostname, together with the capture to construct the destination URL:

rewrite ^/(.*)/$ https://$host/$1 permanent;
like image 52
Richard Smith Avatar answered Oct 21 '22 04:10

Richard Smith