如何在将HTTP重定向到HTTPS时在Nginx中处理400错误 [英] How to handle 400 error in Nginx when redirect HTTP to HTTPS
问题描述
我拥有一个网站,例如HTTP的example.com。考虑到安全的东西,现在我想将HTTP更改为HTTPS。我希望所有老客户仍然能够访问我的网站,即使他们使用example.com,它将通过Nginx重定向到https。
I own a website, like example.com by HTTP. Considering the secure stuff, now I want to change the HTTP to HTTPS. And I hope all the old customers could still be able to visit my website even they use example.com which will be redirect to https via Nginx.
当然,我google了很多,那么我的解决方案是:
Of course, I googled a lot, then my solution is:
upstream www {
server 127.0.0.1:4000;
}
server {
listen 80;
listen 443 ssl;
server_name localhost www example.com;
ssl on;
ssl_certificate /usr/local/etc/docs/example.crt;
ssl_certificate_key /usr/local/etc/docs/example.key;
if ($ssl_protocol = "") {
rewrite ^ https://$host$request_uri? permanent;
}
# below are some other stuff
# ...
}
但是当我访问example.com时,我得到了:
But when I visit example.com, I got:
400错误请求纯HTTP请求已发送到HTTPS端口
400 Bad Request The plain HTTP request was sent to HTTPS port
然后在读取在nginx中重定向,并将error_page配置为497:
Then I change the nginx.conf, after reading Redirect in nginx , and config the error_page by 497:
upstream www {
server 127.0.0.1:4000;
}
server {
listen 80;
listen 443 ssl;
server_name localhost www example.com;
ssl on;
ssl_certificate /usr/local/etc/docs/example.crt;
ssl_certificate_key /usr/local/etc/docs/example.key;
error_page 497 https://$host$request_uri;
# below are some other stuff
# ...
}
然后它工作,一切都很好。但我只是不知道为什么,error_page的解决方案看起来似乎很糟糕。所以在阅读错误>处理nginx 400普通的HTTP请求被发送到HTTPS端口错误,我添加了默认值并删除了ssl。
Then it works, everything is fine. But I just don't know why and the solution of error_page just seems werid. So after reading Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error, I add the default and remove the ssl on.
upstream www {
server 127.0.0.1:4000;
}
server {
listen 80;
listen 443 default ssl;
server_name localhost www example.com;
ssl on;
ssl_certificate /usr/local/etc/docs/example.crt;
ssl_certificate_key /usr/local/etc/docs/example.key;
if ($ssl_protocol = "") {
rewrite ^ https://$host$request_uri? permanent;
}
# below are some other stuff
# ...
}
太棒了!它又有效了。但我不确定:
Great! It works again. But I am not for sure:
- 哪种解决方案正确?
- 如果两者都正确,哪个对SEO更友好?
- Which solution is correct?
- If both correct, which is more friendly for SEO?
推荐答案
解决方案1st真正有线,来自 http://moz.com/learn/seo/redirection,可以发现永久重定向更友好。
Solution 1st is really wired, from http://moz.com/learn/seo/redirection, can find that permanent redirection is more friendly.
server {
listen 80;
server_name www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 default ssl;
server_name www example.com;
ssl on;
ssl_certificate /usr/local/etc/docs/example.crt;
ssl_certificate_key /usr/local/etc/docs/example.key;
# below are some other stuff
# ...
}
这篇关于如何在将HTTP重定向到HTTPS时在Nginx中处理400错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!