一、反向代理Https

(1)先获取https证书(nginx用的)

(2)配置nginx

配置文件:查看配置文件 nginx.conf 路径

 nginx -t

linux配置:

server {
  listen 80;
  listen 443;

  # 代理域名
  server_name xxxx.com; #你要代理的域名

  # 证书配置
  ssl on;
  ssl_certificate /etc/nginx/cert/xxxx.crt; #证书路径
  ssl_certificate_key /etc/nginx/cert/xxxx.key; #证书密钥路径

  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;
  ssl_prefer_server_ciphers on;

  #项目放置的目录
  root xxxxxx;

  # Load configuration files for the default server block.
  include /etc/nginx/default.d/*.conf;

  location / {
    # 转发的本地地址
    proxy_pass http://localhost:80;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;

    # 做https跳转
    proxy_redirect http:// $scheme://;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }

  error_page 404 /404.html;
  location = /40x.html {
  }

  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
  }
}

win配置:

server {
  listen 80;
  listen 443;

  # 代理域名
  server_name xxxx.com; #你要代理的域名

  # 证书配置
  ssl on;
  ssl_certificate /etc/nginx/cert/xxxx.crt; #证书路径
  ssl_certificate_key /etc/nginx/cert/xxxx.key; #证书密钥路径

  ssl_session_cache shared:SSL:1m;
  ssl_session_timeout 5m;

  ssl_ciphers HIGH:!aNULL:!MD5;
  ssl_prefer_server_ciphers on;

  #项目放置的目录
  root xxxxxx;

  location / {
    root html;
    index index.html index.htm;

    # 转发的本地地址
    proxy_pass http://localhost:80;
    proxy_set_header Host $host;

    # 做https跳转
    proxy_redirect http:// $scheme://;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

(3) 重启nginx

nginx.exe -s reload
 
安装win服务重启方式:service.exe restart

二、解决访问跨域问题

例子:前端接口:8001,后端接口8002(前后端都没配置跨域)

(1)修改nginx配置文件(代理给6666端口,注意,6666端口不可以被占用)

server {
  # 监听端口
  listen       6666;
  # 监听地址
  server_name  localhost;

  # 转发的本地地址(前端)
  location / {
    proxy_pass http://localhost:8001;
  }
  # 转发的本地地址(后端)
  location /api {
    proxy_pass http://localhost:8002;
  }
}

(2)重启nginx

(3)测试前端和后端地址

访问地址端口已经变更,项目运行服务端口不变,直接代理给6666端口了

​原来:

前端地址:http://localhost:8001

后端地址:http://localhost:8002/api/getData

更改后:

前端地址:http://localhost:6666

后端地址:http://localhost:6666/api/getData

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐