如何写一个自动跳转页面使 http 根据来路自动跳转到 https 上?

2015-02-10 09:54:22 +08:00
 aruisi
例如输入http://abc.com后自动跳转到https://abc.com
输入http://123.com后自动跳转到httsp://123.com
就是根据用户输入的网址使其都自动加上https://跳转
3716 次点击
所在节点    PHP
22 条回复
virusdefender
2015-02-10 09:59:47 +08:00
chrome://net-internals/#hsts
ryd994
2015-02-10 10:00:51 +08:00
这种事情干嘛php做……
web服务器直接rewrite效率高多了
roychan
2015-02-10 10:06:07 +08:00
Nginx 下可以这么配置:

if ($server_port = 80) {
return 301 https://$server_name$request_uri;
}
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
ihciah
2015-02-10 10:15:14 +08:00
修改.htaccess
或者按照一楼的策略在返回头里添加Strict-Transport-Security:max-age=15768000
Jaylee
2015-02-10 10:25:09 +08:00
server {

listen 80;

server_name www.xx.com;

add_header Strict-Transport-Security max-age=15768000;

return 301 https://$server_name$request_uri;
}
aruisi
2015-02-10 10:38:17 +08:00
@virusdefender
@ryd994
@roychan
@ihciah
@Jaylee 感谢各位,请问如果是IIS的话,能否用html做跳转?
JQ
2015-02-10 13:00:24 +08:00
直接在DNS里面做,DNSMadeasy支持转发的。
luo362722353
2015-02-10 15:40:34 +08:00
Nginx 301永久重定向路过
aruisi
2015-02-10 16:12:40 +08:00
@ihciah 我在apache下用以下.htaccess可以实现,请问这个如何改成nginx的格式?
RewriteEngine on
RewriteBase /
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
aruisi
2015-02-10 16:21:46 +08:00
@luo362722353 是这样么
if ($server_port !~ "^443$"){
set $rule_0 1$rule_0;
}
if ($rule_0 = "1"){
rewrite ^/.*$ https://$server_name$uri redirect;
}
bjzhush
2015-02-10 16:58:16 +08:00
请先Gooooooooooooooooooooooogle
shepherd
2015-02-10 17:13:02 +08:00
ryd994
2015-02-10 18:40:30 +08:00
@roychan
if is evil!!!
直接单独开一个location,单独监听80作跳转即可

@aruisi 不要以apache的思维去想nginx,否则写出来的配置不仅恶心,各种坑少不了
要nginx配置的话@Jaylee 的答案就是正解
你只要去掉现在配置里的listen 80,再在末尾加上这一段就可以了。
不过个人意见return 301 https://$host$request_uri; 对不同请求的灵活性会好一点(?)

@shepherd 完全不对。
roychan
2015-02-10 19:38:47 +08:00
@ryd994 求教 why if is evil..
ryd994
2015-02-10 20:09:33 +08:00
msg7086
2015-02-10 23:08:07 +08:00
@Jaylee 80端口sts无用的。
aruisi
2015-02-10 23:19:39 +08:00
@ryd994 Jaylee的方法是对某个特定的域名的做http强制跳转https吧,我的意思是对所有来到这个页面的http请求根据来路跳转到https也就是说当访问http://abc.com时来到了这个页面然后被自动转向到https://abc.com当http://123.com也来到这个页面也被自动转向到https://123.com就是不是针对某个特定的域名,而是所有来到此页面的请求均被其原来的来路替换为https://跳转。
晕,我说的太绕口了........
ryd994
2015-02-10 23:45:51 +08:00
@aruisi 他的方法没错,server_name又不是只能填一个
RTFM: http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name
$host总是对应当前处理的请求……
Jaylee
2015-02-11 01:04:03 +08:00
@aruisi server_name 可以写xxx.com啊 = =
Jaylee
2015-02-11 01:04:38 +08:00
@aruisi 其实你试试就知道了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/169739

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX