前后端分离项目往往需要配置到同一个服务器上,前端一般使用80端口;后端自定义这里用8080举例。
原先
前端访问 **https://www.xxx.com**
后端接口 **http://xxx.com:8080**
目标
前端访问 **https://www.xxx.com**
后端接口 **https://api.xxx.com** 或 **https://www.xxx.com/api**
此时需要配置后端接口为Https,首先可以直接配置后端项目。
其次可以用Nginx反向代理实现目的。
server {
listen 80;
# 👇前端静态文件
server_name www.xxx.com;
# 将所有HTTP请求通过rewrite指令重定向到HTTPS。
rewrite ^/(.*) https://$server_name$request_uri? permanent;
location / {
root /xxx;
index index.html index.htm;
# 解决刷新页面变成404问题的代码
try_files $uri $uri/ /index.html;
# 将所有HTTP请求通过rewrite指令重定向到HTTPS
rewrite ^(.*)$ https://$host$1;
}
location /api/ {
proxy_pass http://127.0.0.1:8080;
}
}
其次是SSL部分
server {
listen 443 ssl;
# 配置HTTPS的默认访问端口为443。
# 如果未在此处配置HTTPS的默认访问端口,可能会造成Nginx无法启动。
# 如果您使用Nginx 1.15.0及以上版本,请使用listen 443 ssl代替listen 443和ssl on。
# 👇前台地址
server_name www.xxx.com;
# 👇前台路径
root /xxx;
index index.html index.htm;
ssl on;
# 👇前台证书
ssl_certificate /xxx.pem;
ssl_certificate_key /xxxx.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
# 表示使用的加密套件的类型。
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #表示使用的TLS协议的类型。
ssl_prefer_server_ciphers on;
gzip on;
gzip_buffers 32 4K;
gzip_comp_level 6;
gzip_min_length 100;
gzip_types application/javascript text/css text/xml;
gzip_disable "MSIE [1-6]\.";
gzip_vary on;
location / {
# 👇前台路径
root /xxx;
index index.html index.htm;
# 解决刷新页面变成404问题的代码
try_files $uri $uri/ /index.html;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_max_temp_file_size 0;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
}
location ^~/api/ {
# 实际后台服务器地址,此地址就是http的,可以实现https转发http
proxy_pass http://127.0.0.1:8080;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /xxx;
}
}
更新后,执行
nginx -t
nginx -s reload
访问
https://www.xxx/api
成功