在我的app/config/security.yml
文件中,我有:
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
- { path: ^/admin, roles: ROLE_ADMIN, requires_channel: https }
在开发中(使用内置服务器中的symfony),如果我转到localhost/login
,它会将我重定向到https://localhost/login
。
但是,在我的生产网站中,转到example.com/login
,我只看到登录页面。浏览器指示连接不安全。
我的直觉认为它可能与nginx配置文件有关。
server {
listen 80;
listen 443 ssl;
server_name example.com;
root /var/www/symfony/web;
client_max_body_size 500M;
location / {
# try to serve file directly, fallback to app.php
index app.php;
try_files $uri @rewriteapp;
}
location @rewriteapp {
rewrite ^(.*)$ /app.php/$1 last;
}
location ~ ^/app\.php(/|$) {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS on;
}
error_log /var/log/nginx/adam_error.log;
access_log /var/log/nginx/adam_access.log;
}
其中,我或多或少地从here
复制了还有一些需要注意的事项:如果我通过symfony在内部重定向到登录页面(即如果我尝试访问/admin
限制路由或者在不安全连接上登录失败,我会被路由到安全https://example.com/login
网址,但显然不够好,我不希望任何人输入example.com/login
并且没有安全连接。
有人能发现可能出错的地方吗?
答案 0 :(得分:4)
好的,我明白了。在我的nginx配置中:
fastcgi_param HTTPS on;
造成了这个问题。事实证明,当它设置为“on”时,如果初始端口为80,则不会强制重定向到https(我猜symfony认为端口80是使用此配置的https),并且设置为“off” ,它会导致无限重定向(nginx将url重定向到端口80,symfony将url重定向到端口443)。
因此解决方案是在端口80处将其关闭,如果是端口443(ssl端口)则将其打开。
这就是我现在的nginx.conf:
server {
listen 80;
listen 443 ssl;
server_name example.com;
root /path/to/symfony_directory/web;
#if your version of nginx is < 1.11.11, uncomment these next two lines
#as $https will not be defined.
#if ($server_port = 443) { set $https on; }
#if ($server_port = 80) { set $https off; }
location / {
# try to serve file directly, fallback to app.php
# try_files $uri /app.php$is_args$args;
index app.php;
try_files $uri @rewriteapp;
}
location @rewriteapp {
rewrite ^(.*)$ /app.php/$1 last;
}
location ~ ^/app\.php(/|$) {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#NOTE THAT "$https" is defined by nginx to be
# "on" if port 443 and off for port 80 (for version > 1.1.11)
fastcgi_param HTTPS $https;
}
}
答案 1 :(得分:0)
为了在Nginx上强制使用HTTPS,你必须修改你的nginx配置文件,如下所示:
server {
listen 80;
location /login {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
# let the browsers know that we only accept HTTPS
add_header Strict-Transport-Security max-age=2592000;
#Put the rest of your config here
}
来源:Github