E
E
Exsy2021-12-08 11:04:33
Nginx
Exsy, 2021-12-08 11:04:33

Redirect from http to https without a slash at the end, how to implement in nginx?

How to redirect from http to https without trailing slash in nginx?

There is this config:

server {
    server_name test.com;

    listen 192.168.17.175:80;

    return 301 https://$host$request_uri;

    error_log /var/www/test.com/data/logs/test.com-frontend.error.log;
    access_log /var/www/test.com/data/logs/test.com-frontend.access.log;
}


server {
    server_name www.test.com  ;
    listen 192.168.17.175:80;
    listen 192.168.17.175:443 ssl http2 ;

    ssl_certificate "/var/www/httpd-cert/test.com_2021-09-15-05-44_21.crt";
    ssl_certificate_key "/var/www/httpd-cert/test.com_2021-09-15-05-44_21.key";

    add_header Strict-Transport-Security "max-age=31536000" always;

    return 301 $scheme://test.com$request_uri;

    error_log /var/www/test.com/data/logs/test.com-frontend.error.log;
    access_log /var/www/test.com/data/logs/test.com-frontend.access.log;
}


If you enter curl -I http://test.com/it, it turns out that it redirects to https://test.com/ with a slash at the end, but how to do it without?
I tried the rewrite rule:
rewrite ^/(.*)/$ /$1 permanent;
It doesn't work, if without http, then the redirect works without a slash.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vreitech, 2021-12-08
@fzfx

there is no way to do a redirect to https://test.com/without a slash at the end, since a slash is mandatory after the domain name in the URL.

L
Lynn "Coffee Man", 2021-12-08
@Lynn

The path part in the HTTP protocol cannot be empty. When you enter only the domain in the browser, it adds /.
Just because the actual request looks like this:

#   ↓ вот это path и он не может быть пустым
GET / HTTP/1.1
Host: test.com
... прочие заголовки

And when answering mureevms , curl will also add a slash. Here* Rebuilt URL to: http://ya.ru/
$ curl -v 'http://ya.ru'
* Rebuilt URL to: http://ya.ru/
*   Trying 2a02:6b8::2:242...
* TCP_NODELAY set
* Connected to ya.ru (2a02:6b8::2:242) port 80 (#0)
> GET / HTTP/1.1
> Host: ya.ru
> User-Agent: curl/7.58.0
> Accept: */*

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question