我正在尝试在我的Nginx服务器上强制使用www和https。
就像这里的其他问题一样,我实现了以下内容。
server_name example.com www.myexample.com
return 301 https://www.example.com$request_uri;
然后在下面,我们添加以下内容,让我们对其进行加密:
if ($scheme != "https") {
return 301 "https://www.$host$request_uri";
}
当我访问该网站时,它会转到https://www,example.com,但我收到消息“ www.example.com将您重定向了太多次。”
如果我注释掉“让我们加密”添加的位,我仍然会收到重定向消息。
仅当我注释掉以下内容时,它才起作用:
return 301 https://www.example.com$request_uri;
有人对如何设置此方法有更好的主意吗?
我看到了另一个答案,但是OP正在使用cloudflare。我没有使用任何CDN。
谢谢
这是我的全部信息。我将第一个返回301行注释掉了,因为它导致了太多的重定向: NGINX:版本1.10.3 Ubuntu:16.04.3 LTS(xenial)
# Default server configuration
#
server {
listen 80;
listen [::]:80;
client_max_body_size 25M;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/example.com/html;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com;
# return 301 https://www.example.com$request_uri;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.php?q=$uri&$args;
}
# hide user.ini file
location ~ ^/\.user\.ini {
deny all;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
include snippets/fastcgi-php.conf;
#
# # With php7.0-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php7.0-fpm:
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
}
location ~* \.(pdf)$ {
expires 30d;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
if ($scheme != "https") {
return 301 https://www.$host$request_uri;
} # managed by Certbot
}
答案 0 :(得分:2)
如果您正在使用certbot进行加密,并且正在Web服务器配置中插入行,那是因为您有意或无意避免使用certonly
选项。
如果您不希望certbot修改您的配置文件,请按以下方式使用它:
certbot certonly --standalone --preferred-challenges http -d example.com
关于重定向,您可以删除您的重定向,然后将其从Certbot中删除,因为该重定向正在检查协议是否为 https ,如果不是,则为应用重定向。
if ($scheme != "https") {
return 301 "https://www.$host$request_uri";
}
我会像这样使用它,如果要确保将其重定向到特定域而不是将其保留给标头请求,请替换$ host变量:
if ($scheme != "https") {
return 301 "https://www.example.com$request_uri";
}
ps。您应该发布完整的virtualhost配置,同时包含用于http和https的两个服务器块,以查看是否还有其他问题。