我想通过使用位置块的nginxconfiguration在我的应用程序中强制HTTPS和apex域名(例如https://example.com )。 我目前有以下nginx_app.conf文件(它与apex和www子域以及http和https一起工作):
location / { try_files $uri @rewriteapp; } location @rewriteapp { rewrite ^(.*)$ /app.php/$1 last; } location ~ ^/(app|config)\.php(/|$) { # fastcgi_pass directives go here... }
为了强制apex域和https,我尝试使用if语句,如下所示,检查$ scheme和$ hostvariables,但是出现一个页面没有正确redirect的错误。 我还添加了一个HSTS指令 。
location / { if ($scheme = http) { rewrite ^/(.*) https://$host/$1 permanent; } if ($host = www.example.com) { rewrite ^/(.*) https://example.com/$1 permanent; } try_files $uri @rewriteapp; } location @rewriteapp { rewrite ^(.*)$ /app.php/$1 last; } location ~ ^/(app|config)\.php(/|$) { # fastcgi_pass directives go here... add_header Strict-Transport-Security "max-age=86400"; }
用nginxconfiguration强制http和apex域的正确方法是什么? 顺便说一下,我使用heroku(与DNSimple)部署我的应用程序,所以我希望以下两个域的工作: https ://example.herokuapp.com和https://example.com 。
更新:我试着移动位置块外的if语句到默认的服务器块(点击这里) ,并改变重写为返回如下,但它仍然无法正常工作。 请求http时,仍然出现“页面不能正确redirect”,请求www子域名时出现“无法连接错误”。
if ($scheme = http) { return 301 https://$host$request_uri; } if ($host = www.example.com) { return 301 https://example.com$request_uri; } location / { try_files $uri @rewriteapp; } location @rewriteapp { rewrite ^(.*)$ /app.php/$1 last; } location ~ ^/(app|config)\.php(/|$) { # fastcgi_pass directives go here... add_header Strict-Transport-Security "max-age=86400"; }
1)这里的问题可能是Heroku负载平衡器。 当请求访问您的应用程序时,请求再次HTTP。 这只是内部路由。 你不能testing$scheme 。 但是Heroku在这些请求上设置了一个$http_x_forwarded_proto标头。
if ($http_x_forwarded_proto != "https") { return 301 https://$host$request_uri; }
来源: https : //discussion.heroku.com/t/force-ssl-and-no-www-with-nginx-configuration/856
2a)为了引导到no-www,你可以使用这个:
server { listen <%= ENV["PORT"] %>; server_name "~^www\.(.*)$"; return 301 https://$1$request_uri; }
对于testing,您应该使用302而不是301,因为浏览器将caching301redirect。
这个也会把你redirect到https。 但只能从www子域,所以你必须保持上面的$http_x_forwarded_protoredirect。
2b)另一个select是使用www子域的服务器块,并将其redirect到非www域,如下所示:
server { listen <%= ENV["PORT"] %>; server_name www.example.com; location / { return 301 https://example.com$request_uri; } } server { listen <%= ENV["PORT"] %>; server_name example.com; location / { try_files $uri $uri/ /index.html =404; } }
<%= ENV["PORT"] %>代码来自buildpack 。 在Heroku上,你不能听港80。
最好的办法是做一个301redirect。
server { listen 80; return 301 https://$host$request_uri; }