1
votes

I have an Nginx server config that already redirects http requests to https, but I'm trying to figure out the proper way to modify this code or completely change it to redirect http requests to https and add a trailing forward slash /, when the url does not contain one. These redirects should also ensure that query parameters still exist despite the redirect. I have seen where most answers to similar questions to mine have referenced ^/(.*)/$ as the code for adding a forward slash, but I'm not sure how to use it and if I should use a rewrite over an if. Can anyone help clear up my confusion?

nginx.config:

upstream nodejs {
    server 127.0.0.1:8081;
    keepalive 256;
}

server {
    listen 8080;

    if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }

    location / {
        proxy_pass  http://nodejs;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP   $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    gzip on;
    gzip_comp_level 4;
    gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

}

Goal:

http://www.example.com/page-one -> http://example.com/page-one/
http://example.com/page-two -> https://www.example.com/page-two/
https://www.example.com/page-three?page=2 -> https://www.example.com/page-three/?page=2
1
The rewrite directive will append the query string to the rewritten URL, unless a trailing ? is added. - Richard Smith
Got it. That is good to know. Are you aware of the proper rewrite method to achieve what I'm asking above? - cphill

1 Answers

2
votes

The three steps in your goals are each performed in different ways. The first step is best achieved using separate server blocks. The second step you already have in your question. The third step uses a rewrite statement.

For example:

server {
    listen 8080 default_server;
    return http://example.com$request_uri;
}
server {
    listen 8080;
    server_name example.com;

    if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }

    rewrite ^(.*[^/])$ $1/ permanent;

    ...
}

The existing query string is also appended to the rewritten URL. See this document for details.