HowTo: Nginx Redirect HTTP To HTTPS with Rewrite 301 Rules

ht‮t‬ps://www.lautturi.com
HowTo: Nginx Redirect HTTP To HTTPS with Rewrite 301 Rules

To redirect HTTP traffic to HTTPS in Nginx, you can use the rewrite directive with a permanent 301 redirect.

Here is an example configuration that will redirect all HTTP traffic to the corresponding HTTPS URL:

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;
    ...
}

This configuration will listen for incoming HTTP requests on port 80 and redirect them to the HTTPS version of the same URL using a permanent 301 redirect.

You can also use the $scheme variable to redirect HTTP traffic to HTTPS based on the value of the X-Forwarded-Proto header, which is set by a load balancer or reverse proxy. This can be useful if you are running Nginx behind a load balancer or reverse proxy and want to redirect HTTP traffic to HTTPS even if the traffic is not directly coming to Nginx.

Here is an example configuration that will redirect HTTP traffic to HTTPS based on the value of the X-Forwarded-Proto header:

server {
    listen 80;
    server_name example.com www.example.com;
    if ($http_x_forwarded_proto = "http") {
        return 301 https://$server_name$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;
    ...
}

This configuration will listen for incoming HTTP requests on port 80 and check the value of the X-Forwarded-Proto ,if it's http , then redirect HTTP traffic to HTTPS .

Created Time:2017-10-29 22:08:44  Author:lautturi