Redirecting to SSL using nginx

2019-01-17 07:52发布

I have http:// and https:// on the same host like the following:

server {

    listen   80;
    listen   443 ssl;

    ...
    ...
}

What I need to do is redirecting users who access my shop to https://. The problem is I have many languages:

https://mydomain.com/en/shop https://mydomain.com/fr/shop etc...

I tried this and it didn't work (nginx: configuration file /etc/nginx/nginx.conf test failed):

if ($server_port = 80) {
    location (en|fr)/shop {
        rewrite ^ https://$host$request_uri permanent;
    }
}

标签: nginx
5条回答
Viruses.
2楼-- · 2019-01-17 08:21

Or better yet, avoiding the hardcoded server name

server {
  listen 80;
  rewrite (.*) https://$http_host$1 permanent;
}
查看更多
姐就是有狂的资本
3楼-- · 2019-01-17 08:22

Ideally, avoiding if statements while preserving the trailing path:

server {
  listen 80;
  server_name example.com;
  rewrite (.*) https://example.com$1 permanent;
}

permanent takes care of the 301.

查看更多
混吃等死
4楼-- · 2019-01-17 08:24

In order to use regular expressions for matching locations, you need to prefix the expression with either ~ or ~*:

if ($server_port = 80) {
    location ~ (en|fr)/shop {
        rewrite ^ https://$host$request_uri permanent;
    }
}

From the documentation:

To use regular expressions, you must use a prefix:

  1. "~" for case sensitive matching
  2. "~*" for case insensitive matching

Since nginx does't allow location blocks to be nested inside of if blocks, try the following configuration:

if ($server_port = 80) {
    rewrite ^/(en|fr)/shop https://$host$request_uri permanent;
}
查看更多
放荡不羁爱自由
5楼-- · 2019-01-17 08:24

another way with error_page 497

server {
    listen 80;
    listen 443;

    ssl on;
    error_page 497  https://$host$request_uri;
    ssl_certificate     /etc/ssl/certs/ssl-cert-snakeoil.pem;
    ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;
...
查看更多
Ridiculous、
6楼-- · 2019-01-17 08:28

It would also be more of an NGINX best practice to do a 301 redirect instead of using the if statement (see Server name on http://wiki.nginx.org/Pitfalls). I created a gist with an nginx.conf configured for SSL, Rails and Unicorn

https://gist.github.com/Austio/6399964

Here would be the relevant section for yours.

server {
    listen      80;
    server_name domain.com;
    return 301  https://$host$request_uri;
}
查看更多
登录 后发表回答