来一篇简单的。
Nginx服务配置ssl访问,使用默认的443端口。
Nginx ssl module
配置之前首先需要确认Nginx是否已经启用了ssl模块:
[root@erpTest sbin]# ./nginx -V
nginx version: nginx/1.19.9
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
看到configure arguments: 这一行里有 --with-http_ssl_module 就是OK的,如果没有的话需要首先搞定它,网上查一下,Nginx增加ssl 模块即可。
获取SSL证书
自己生成也好,或者从域名服务商那里去获取也可以,阿里云从2023年11月份修改了免费SSL证书的策略,12月有效期变更为3个月,无非就是不想提供免费SSL证书了,没办法,如果要用阿里云提供的免费证书的话,就需要每3个月更换一次,一个域名一年给20个免费证书。
之后下载证书(pem和key文件),上传到服务器上,准备配置。
配置
配置之前最好备份一下nginx.conf文件,否则一旦配置文件被破坏,以前的配置又找不回来,还得重头再来。
我的需求是443端口的访问上来之后,转发到本地的8088,配置方式如下:
server {listen 443 ssl;server_name your.domain.name;ssl_certificate /usr/local/nginx/conf/cert/cert.pem;ssl_certificate_key /usr/local/nginx/conf/cert/cert.key;ssl_session_cache shared:SSL:1m;ssl_session_timeout 5m;ssl_ciphers HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers on;location /prod-api/ {proxy_pass your-forward-addrss:port;proxy_set_header Host 127.0.0.1;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';}location / {root /newERP/qd;index index.html index.htm;if (!-e $request_filename) {rewrite ^(.*)$ /index.html?s=$1 last;break;}add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';}}
重启nginx
注意,我这里通过如下命令:
cd /usr/local/nginx/sbin
./nginx -s reload
重启之后,通过命令:
netstat -ntlp|grep nginx
是没有看到443端口有任何服务的,所以来一次彻底重启:
./nginx -s stop
./nginx
之后:
[root@erpTest conf]# netstat -ntlp |grep nginx
tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 19607/nginx: master
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 19607/nginx: master
443端口的服务起来了,服务端准备好了。但是却不能访问。
防火墙
如果你是阿里云服务器,第一步先去阿里云控制台的安全策略中放开443端口。
放开之后,还是不能访问。
所以就去检查一下本机防火墙。
[root@erpTest conf]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemonLoaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)Active: active (running) since Wed 2024-01-17 16:32:49 CST; 16min agoDocs: man:firewalld(1)Main PID: 19835 (firewalld)CGroup: /system.slice/firewalld.service└─19835 /usr/bin/python2 -Es /usr/sbin/firewalld --nofork --nopidJan 17 16:32:49 erpTest systemd[1]: Starting firewalld - dynamic firewall daemon...
Jan 17 16:32:49 erpTest systemd[1]: Started firewalld - dynamic firewall daemon.
Jan 17 16:32:49 erpTest firewalld[19835]: WARNING: AllowZoneDrifting is enabled. This is considered an insecure ... now.
Hint: Some lines were ellipsized, use -l to show in full.
看到Active: active (running)这一行,说明本地防火墙正在运行中。
检查443端口是否放行:
[root@erpTest conf]# firewall-cmd --query-port=443/tcp
no
比如我这里查询443端口,本地防火墙是不放行的。
修改本地防火墙规则,放行443端口:
firewall-cmd --permanent --add-port=443/tcp
之后需要重启防火墙:
# 开启
service firewalld start
# 重启
service firewalld restart
# 关闭
service firewalld stop
OK了,443端口能正常访问了。