购买SSL证书后,我一直试图强制所有页面加密https和www。
https://www.exampl.com工作和安全,但只有完全键入它。 www.example.com或example.com仍然指向http。
我们使用nginx作为代理,需要在那里输入重写。我通过Putty进行SSH / root访问。我通过输入putty访问了nginx.conf。
怎么办?我是否在此页面上输入了nginx命令?从光标开始?任何命令行首先?
HTTPS:
.htaccess - 在我发现我必须输入nginx之前给出的原始代码
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
Nginx代码转换器 - 这是它在转换器上显示的方式。一切都在正确的线上吗?
# nginx configuration location / {
if ($http_host ~* "^example.com"){
rewrite ^(.*)$ http://example.com/$1 redirect; } }
然后
万维网
.htaccess - 在我发现我必须输入nginx之前给出的原始代码
#Force www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
Nginx代码转换器 - 这是它在转换器上显示的方式。一切都在正确的路线上吗?
# nginx configuration location / {
if ($http_host ~* "^example.com"){
rewrite ^(.*)$ http://www.example.com/$1 redirect; }
}
我保存了吗?重新开始?
任何帮助将不胜感激。我已经和我斗争了好几个星期。我的托管公司尽可能地帮助,现在我正在学习......或者我应该停止并聘请开发人员? $$$
谢谢
实现WWW和HTTPS重定向的最佳方法是在Nginx配置中创建一个新的server
部分:
server {
listen 80; #listen for all the HTTP requests
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
你还必须执行https://example.com到https://www.example.com重定向。这可以使用类似于以下的代码完成:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate ssl.crt; #you have to put here...
ssl_certificate_key ssl.key; # ...paths to your certificate files
return 301 https://www.example.com$request_uri;
}
当然,每次更改后都必须重新加载Nginx配置。以下是一些有用的命令:
检查配置中的错误:
sudo service nginx configtest
重新加载配置(这足以使更改“工作”):
sudo service nginx reload
重启整个网络服务器:
sudo service nginx restart
重要的提示:
你所有的server
部分必须在http
部分内(或在http
部分包含的文件中):
http {
# some directives ...
server {
# ...
}
server {
# ...
}
# ...
}
以下解决方案似乎清晰简单,一切都在一个服务器块中定义。因此,通过此设置,我将所有内容强制为https://www.domain.tld,因此这两个处理程序在HTTPS上都是非HTTPS和非WWW。有两个IF,但是如果你不想复制整个SSL块两次来处理它......这就是这样做的方法。
server {
listen 80;
listen 443 ssl;
server_name domain.tld www.domain.tld;
# global HTTP handler
if ($scheme = http) {
return 301 https://www.domain.tld$request_uri;
}
# global non-WWW HTTPS handler
if ($http_host = domain.tld){
return 303 https://www.domain.tld$request_uri;
}
}
甚至更好的解决方案,以避免IF:
# Redirect all traffic from HTTP to HTTPS
server {
listen 80;
server_name example.com www.example.com;
# Destination redirect base URI
set $RURI https://www.example.com;
location / {return 301 $RURI$request_uri;}
}
# Redirect non-WWW HTTPS traffic to WWW HTTPS
server {
listen 443 ssl;
# NOTE: SSL configuration is defined elsewhere
server_name example.com;
return 301 $scheme://www.$host$request_uri;
}
# MAIN SERVER BLOCK
server {
listen 443 ssl;
# NOTE: SSL configuration is defined elsewhere
server_name www.example.com;
}
如果您有启用站点的目录,请不要使用“http”top指令。只需在启用站点的目录中创建另一个文件(具有任何名称),该目录具有:
server {
listen 80; #listen for all the HTTP requests
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
并注释掉这条线
listen 80;
其中server_name在为www.example.com提供服务的另一个文件中是相同的