在我的 nginx 配置中,我打算达到以下目的:
- 将 www 转发至非 www
- 将 https 转发到 http
- 仅在 uri 上使用具有“secure”模式的 https
下面的代码实现了目标,除了点 3Chrome 显示空白页并显示错误“此网页有重定向循环”。有人能告诉我正确的配置吗,以及/或者有更好的代码吗?
#redirect www to non-www
server {
listen 80;
server_name www.example.org;
return 301 http://example.org$request_uri;
}
#redirect https to http, for both www and non-www
#but process https for uri with pattern 'secure'
server {
ssl_certificate /home/mydomain/ssl.cert;
ssl_certificate_key /home/mydomain/ssl.key;
listen 443 ssl;
server_name www.example.org example.org;
root /home/mydomain/public_html/mydomain/public;
index index.php;
access_log /var/log/virtualmin/example.org_access_log;
error_log /var/log/virtualmin/example.org_error_log;
#if has pattern 'secure', just process
#---problem is here, chrome result 'This webpage has a redirect loop'---
location ~ ^/(secure) {
try_files $uri $uri/ /index.php$is_args$args;
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
return 301 http://example.org$request_uri;
}
server {
listen 80;
server_name example.org;
root /home/mydomain/public_html/mydomain/public;
index index.php;
access_log /var/log/virtualmin/example.org_access_log;
error_log /var/log/virtualmin/example.org_error_log;
#rewrite to https if has pattern secure
location ~ ^/(secure) {
#rewrite ^(.*) https://$host$1 permanent;
return 301 https://example.org$request_uri;
}
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
答案1
通过在应用程序级别执行 SSL 重定向来结束
Route::filter('check.ssl', function()
{
$segment = Request::segment(1);
if ( ( $segment == 'secure') && ( !Request::secure() ) )
return Redirect::secure(Request::getRequestUri());
else if ( ( $segment != 'secure') && ( Request::secure() ) )
return Redirect::to(Request::path(), 302, array(), false);
});
答案2
替换为:
location ~ ^/(secure) {
try_files $uri $uri/ /index.php$is_args$args;
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
return 301 http://example.org$request_uri;
有了这个:
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
if ( $uri !~ ^/(secure) ){
return 301 http://riwa.nu$request_uri;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
而且它应该能正常工作:-)