nginx配置http跳转https
- 格式:pdf
- 大小:70.33 KB
- 文档页数:2
nginx配置http跳转https
⼀、需求简介
我总结了三种⽅式,跟⼤家共享⼀下
⼆、nginx的rewrite⽅法
思路
这应该是⼤家最容易想到的⽅法,将所有的http请求通过rewrite重写到https上即可
配置
server {
listen 192.168.1.111:80;
server_name test.com;
rewrite ^(.*)$ https://$host$1 permanent;
}
总体的server模块配置:
server {
listen 80;
server_name shfxx.test.com;
rewrite ^(.*)$ https://$host$1 permanent;
}
server {
listen 443 ssl;
ssl on;
ssl_certificate /usr/local/nginx/conf/ssl/START-smartcampus-org-cn.pem;
ssl_certificate_key /usr/local/nginx/conf/ssl/START-smartcampus-org-cn.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-RC4-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AE
:!eNULL:!EXPORT:!DES:!3DES:!MD5:!DSS:!PKS;
ssl_session_cache builtin:1000 shared:SSL:10m;
server_name shfxx.test.com;
access_log /data/wwwroot/sfzxxx/logs/access_campus.log combined;
error_log /data/wwwroot/sfzxxx/logs/error_campus.log;
root /data/wwwroot/sfzxxx/campus;
index index.html index.htm index.php;
location / {
if (!-e $request_filename) {
rewrite ^/admin/(.*)$ /admin.php/$1 last;
rewrite ^/(.*)$ /index.php/$1 last;
}
}
location ~ [^/]\.php(/|$) {
#fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi.conf;
}
}
三、nginx的497状态码
error code 497
497 - normal request was sent to HTTPS
解释:当此虚拟站点只允许https访问时,当⽤http访问时nginx会报出497错误码
思路
配置
server {
listen 192.168.1.11:443; #ssl端⼝
listen 192.168.1.11:80; #⽤户习惯⽤http访问,加上80,后⾯通过497状态码让它⾃动跳到443端⼝
server_name test.com;
#为⼀个server{......}开启ssl⽀持
ssl on;
#指定PEM格式的证书⽂件
ssl_certificate /etc/nginx/test.pem;
#指定PEM格式的私钥⽂件
ssl_certificate_key /etc/nginx/test.key;
#让http请求重定向到https请求
error_page 497 https://$host$uri?$args;
}
四、index.html刷新⽹页
思路
上述两种⽅法均会耗费服务器的资源,我们⽤curl访问baidu.com试⼀下,看百度的公司是如何实现baidu.com向www.baidu.com的跳转
可以看到百度很巧妙的利⽤meta的刷新作⽤,将baidu.com跳转到www.baidu.com.因此我们可以基于http://test.com的虚拟主机路径下也写⼀个index.html,内容就是http向https
的跳转
index.html
[html]
nginx虚拟主机配置server {
listen 192.168.1.11:80;
server_name test.com;
location / {
#index.html放在虚拟主机监听的根⽬录下
root /srv/www/http.test.com/;
}
#将404的页⾯重定向到https的⾸页
error_page 404 https://test.com/;
}