使用nginx代理vue前端项目

459 阅读1分钟

上传前端build后的文件到服务器指定目录

如图上传到了/app/nginx/html/目录下,此目录对应docker容器的/usr/share/nginx/html目录。

image.png

nginx.conf配置文件内容


user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;

    server {
        #SSL 默认访问端口号为 443
        listen 443 ssl; 
        #请填写绑定证书的域名
        server_name liboshuai.com; 
        #请填写证书文件的相对路径或绝对路径
        ssl_certificate /usr/share/nginx/html/liboshuai.com_bundle.crt; 
        #请填写私钥文件的相对路径或绝对路径
        ssl_certificate_key /usr/share/nginx/html/liboshuai.com.key; 
        ssl_session_timeout 5m;
        #请按照以下协议配置
        ssl_protocols TLSv1.2 TLSv1.3; 
        #请按照以下套件配置,配置加密套件,写法遵循 openssl 标准。
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; 
        ssl_prefer_server_ciphers on;

        # 设置网站首页,请求转发https://liboshuai.com/ 到 服务器前端页面
        location / {
            root /usr/share/nginx/html/pulsar/dist; # 设置根路径(一定要是容器里面的路径)
            index index.html index.html; # 网站主页地址
            try_files $uri $uri/ /index.html; # 如果找不到静态资源,就会重定向到主页
        } 

        # 请求转发https://liboshuai.com/pulsar/到http://liboshuai.com:8080/,解决浏览器https内容调用http接口限制问题
        location /pulsar/ {
            proxy_pass http://liboshuai.com:8080/;
        }
    }
    
    # 强制重定向http到https
    server {
        listen 80;
        server_name liboshuai.com;
        rewrite ^(.*)$ https://${server_name}$1 permanent; 
    }
  
}

注意点

  1. 前端项目的文件一定要放到docker挂载的目录里面
  2. nginx.conf里面关于路径的配置,一定是基于docker容器的目录配置的,而不是宿主机的目录。
  3. nginx里面进行了请求转发,前端调用对应的后端接口路径也要进行变更。例如:请求转发https://liboshuai.com/pulsar/到http://liboshuai.com:8080/,则之前前端调用后端是http://liboshuai.com:8080,就需要变更为https://liboshuai.com