Requirements Introduction
Based on Nginx built an HTTPS access to the virtual host, listening to the domain name is test.com, but many users do not know the difference between HTTPS and HTTP, it will be easy to knock into http://test.com, this time will report 404 errors, so I need to do Forced jump of HTTP to HTTPS based on test.com domain name
I've summed up three ways to share with you
The rewrite method of Nginx
Ideas
This should be the easiest way for everyone to think about it, and rewrite all HTTP requests via rewrite to HTTPS.
Configuration
server {
Listen 192.168.1.111:80;
server_name test.com;
Rewrite ^ (. *) $ https://$host $ permanent;
}
Once this virtual host is built, you can rewrite all of the http://test.com's requests to https://test.com.
Nginx 497 Status Code
Error code 497
497-normal request was sent to HTTPS
Explanation: When this virtual site allows only HTTPS access, Nginx will report a 497 error code when it is accessed with HTTP
Ideas
Use the Error_page command to redirect the link of the 497 status code to the domain name of https://test.com
Configuration
server {
Listen 192.168.1.11:443; #ssl端口
Listen 192.168.1.11:80; #用户习惯用http访问, plus 80, followed by a 497 status code to automatically jump to port 443.
server_name test.com;
#为一个server {...} Turn on SSL support
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 Refresh Web page
Ideas
Both of these methods will consume the resources of the server, we use Curl to access baidu.com try to see how Baidu's company is to achieve baidu.com to www.baidu.com jump
Can see Baidu very clever use Meta refresh function, will baidu.com jump to www.baidu.com. So we can also write a index.html based on the http://test.com of the virtual host path, the content is http to https jump
Index.html
[HTML] view Plaincopyprint?
< HTML >
<Meta http-equiv="Refresh" content="0;url=https://test.com/">
</ HTML >
Nginx Virtual Host Configuration
server {
Listen 192.168.1.11:80;
server_name test.com;
Location/{
#index. HTML is placed in the root directory of the virtual host listener
root/srv/www/http.test.com/;
}
#将404的页面重定向到https的首页
Error_page 404 https://test.com/;
Nginx enforces HTTPS access (HTTP jumps to HTTPS