17

我在同一主机上有 http:// 和 https:// ,如下所示:

server {

    listen   80;
    listen   443 ssl;

    ...
    ...
}

我需要做的是将访问我商店的用户重定向到 https://。问题是我有很多语言:

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

我试过了,但没有用(nginx: configuration file /etc/nginx/nginx.conf test failed)

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

5 回答 5

47

执行 301 重定向而不是使用 if 语句也更像是 NGINX 最佳实践(请参阅http://wiki.nginx.org/Pitfalls上的服务器名称)。我创建了一个为 SSL、Rails 和 Unicorn 配置的 nginx.conf 的要点

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

这将是您的相关部分。

server {
    listen      80;
    server_name domain.com;
    return 301  https://$host$request_uri;
}
于 2013-09-18T14:36:18.897 回答
11

或者更好的是,避免硬编码的服务器名称

server {
  listen 80;
  rewrite (.*) https://$http_host$1 permanent;
}
于 2014-03-21T02:23:07.893 回答
6

为了使用正则表达式来匹配locations,您需要在表达式前面加上~or ~*

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

文档中:

要使用正则表达式,您必须使用前缀:

  1. "~"用于区分大小写的匹配
  2. "~*"用于不区分大小写的匹配

由于 nginx 不允许将location块嵌套在if块内,请尝试以下配置:

if ($server_port = 80) {
    rewrite ^/(en|fr)/shop https://$host$request_uri permanent;
}
于 2013-08-30T00:48:39.287 回答
2

理想情况下,在保留尾随路径的同时避免使用 if 语句:

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

永久负责301。

于 2014-03-21T01:14:36.597 回答
2

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;
...
于 2014-04-15T17:37:22.713 回答