我在 Laravel Forge 上使用 Let's Encrypt 设置了 HTTPS,并使用 Laravel 中间件将非安全域重定向到安全域:
if ( env('APP_ENV') === 'production' ) {
$request->setTrustedProxies([$request->getClientIp()]);
if ( !$request->secure() ) {
return redirect()->secure($request->getRequestUri());
}
}
return $next($request);
这是我的example.com
(不是实际的域)Nginx 配置:
# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/example.com/before/*;
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
root /home/forge/example.com/public;
# FORGE SSL (DO NOT REMOVE!)
ssl_certificate /etc/nginx/ssl/example.com/120143/server.crt;
ssl_certificate_key /etc/nginx/ssl/example.com/120143/server.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers '[...]';
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/nginx/dhparams.pem;
index index.html index.htm index.php;
charset utf-8;
# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/example.com/server/*;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
access_log off;
error_log /var/log/nginx/example.com-error.log error;
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/example.com/after/*;
这是我的www.example.com
配置:
# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/www.example.com/before/*;
server {
listen 80;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/www.example.com/after/*;
一切正常,HTTP重定向到HTTPS,www重定向到非www,但我想做相反的事情并将非www重定向到www。我添加了
return 301 $scheme://www.example.com$request_uri;
toexample.com
并在配置中将其注释掉www.example.com
以删除循环,但它不起作用:
www.example.com redirected you too many times.
我也尝试将非www配置的内容复制到www配置,并在那里听443,但它仍然无休止地重定向。我究竟做错了什么?感谢您的时间。