nginx配置ssl证书
1.官网下载
nginx官网下载地址
下载后,放到指定某一文件夹下并解压缩,之后cmd进入解压后的目录下,执行start nginx.exe命令
start nginx.exe
然后在浏览器中访问默认监听80端口
http://localhost:80
浏览器访问有nginx表示启动成功!
2.更改nginx配置
nginx配置文件位置如下图:
配置文件在解压后的目录下conf目录下
在conf目录下新建cert目录,将自己买的证书放到该目录下,我这边nginx证书是.pem,.key格式的两个文件
配置ssl证书,在nginx.conf配置文件中,新添加server监听(原监听保留,将原监听的server下要用的的location都复制到443监听中),nginx中,https协议端口是443,相当于https中的80端口访问
如果想要http强制转为https协议,则只需要在原监听server配置中,增加重定向配置即可
重定向配置
rewrite ^(.*)$ https://$host$1 permanent; #把http的域名请求转成https
nginx配置如下:
############## 原监听server配置 ##############
server {
listen 80;
server_name localhost 127.0.0.1;
rewrite ^(.*)$ https://$host$1 permanent; #把http的域名请求转成https
location / {
root E:/disk_software/IT/nginx/nginx-1.24.0/html/index/dist; #前端项目路径
index index.html;
}
location /mobile {
alias E:/disk_software/IT/nginx/nginx-1.24.0/html/mobile/dist; #手机端项目路径
index index.html;
}
# 后端api服务端(反向代理访问api,对外还是https访问api接口)
location /api/ {
proxy_pass http://localhost:1220/api/;
}
location /images {
proxy_pass http://localhost:1220;
}
#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;
}
}
############## 新增加的配置ssl证书的server配置 ##############
server {
listen 443 ssl;
server_name localhost 127.0.0.1;
#ssl on;
ssl_certificate cert/证书名.pem;
ssl_certificate_key cert/证书名.key;
proxy_ignore_client_abort on;
#access_log log日志;
#error_log error日志;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
proxy_set_header X-real-uri $request;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
location / {
root E:/disk_software/IT/nginx/nginx-1.24.0/html/index/dist; #前端项目路径
index index.html;
}
location /mobile {
alias E:/disk_software/IT/nginx/nginx-1.24.0/html/mobile/dist; #手机端项目路径
index index.html;
}
# 后端api服务端(反向代理访问api,对外还是https访问api接口)
location /api/ {
proxy_pass http://localhost:1220/api/;
}
location /images {
proxy_pass http://localhost:1220;
}
#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;
}
}
配置好后,重启nginx,然后浏览器访问测试就好
nginx启动,停止,刷新配置命令如下:
(注意:命令需要安装目录下执行——即能看到nginx.exe可执行文件所在目录)
1.nginx启动命令
start nginx.exe
2.停止命令
nginx.exe -s stop
3.刷新配置命令
nginx.exe -s reload
参考博文:
nginx(NGINX)详细下载安装及使用教程
https://www.kuangstudy.com/网站—Nginx配置反向代理 和 https