nginx 配置 http 强转 https
问题描述
如今 https 比 http 更加安全,可以用 nginx 配置一下 http 请求强转 https;
解决方案
方法一:采用nginx的497状态码
server {
listen 8080 default_server;
listen [::]:8080 default_server;
# SSL configuration
#
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name yculcy.cn; #填写绑定证书的域名
ssl on;
ssl_certificate ./conf/1_yculcy.cn_bundle.crt;
ssl_certificate_key ./conf/2_yculcy.cn.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #按照这个协议配置
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;#按照这个套件配置
ssl_prefer_server_ciphers on;
# 根据状态码 497 当网站只允许https访问时,当用http访问时nginx会报出497错误码
error_page 497 https://$host$request_uri;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
}
方法二:用 rewrite 重定向
server {
listen 8080 default_server;
listen [::]:8080 default_server;
rewrite ^(.*)$ https://$host$1 permanent; # 这是ngixn早前的写法,现在还可以使用。
}