nginx http转 https
方式1:使用rewrite指令
rewrite ^(.*) https://$server_name$1 permanent;
server {
listen 80;
server_name domain.com;
rewrite ^(.*) https://$server_name$1 permanent;
}
server {
listen 443 ssl;
server_name domain.com;
ssl on;
ssl_certificate /etc/nginx/ssl/domain.com.crt;
ssl_certificate_key /etc/nginx/ssl/domain.com.crt;
# other
}
upstream tomcat1{
ip_hash;
server 192.168.0.188:8085;
server 192.168.0.187:8085;
}
server {
listen 80;
server_name www.baidu.com;
rewrite ^(.*) https://$server_name$1 permanent;
charset utf-8;
#access_log logs/host.access.log main;
#后台接口地址
location / {
root html;
index index.html index.htm;
#proxy_pass http://tomcat1/;
}
location /Wx/ {
proxy_pass http://127.0.0.1:8081/Wx/;
proxy_connect_timeout 15s;
proxy_send_timeout 15s;
proxy_read_timeout 15s;
}
location /csm/ {
proxy_pass http://127.0.0.1:8082/csm/;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# HTTPS server
#
server {
listen 443 ssl;
server_name www.baidu.com; #修改为您证书绑定的域名。
ssl_certificate cert/server.crt; #替换成您的证书文件的路径。
ssl_certificate_key cert/server.key; #替换成您的私钥文件的路径。
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
proxy_pass http://tomcat1/;
}
}
方式2:使用return指令
server {
listen 80;
server_name www.baidu.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name www.baidu.com;
ssl on;
ssl_certificate cert/server.crt; #替换成您的证书文件的路径。
ssl_certificate_key cert/server.key; #替换成您的私钥文件的路径。
# other
}
方式3:使用error_page指令
只允许HTTP来访问时,用HTTP访问会让Nginx报497错误,然后利用error_page将链接重定向至HTTPS上。
server {
listen 80;
listen 443 ssl;
server_name www.baidu.com;
ssl on;
ssl_certificate /etc/nginx/ssl/domain.com.crt;
ssl_certificate_key /etc/nginx/ssl/domain.com.crt;
# other
error_page 497 https://$server_name$request_uri;
}
使用error_page指令时,将http和https的监听配置写在同一个server块中,对应的其他配置也需要在该server配置块中完成。
需要注意的是,此时需要将error_page指令语句写在最后,否则不能生效。