一个 nginx 通过不同域名映射多个前端项目

场景

域名解析到某台服务器,有两个前端服务(原生门户、vue后台管理),安装了一个nginx,通过此域名及子域名映射到不同的前端服务上

思路

将nginx的配置文件分为几个子配置,根据域名读取不同的前端index.html

配置文件

默认配置

添加include映射子配置

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;
    #添加include映射子配置
    include       /etc/nginx/vhost/*.conf;
    default_type  application/octet-stream;

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

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
}
子配置

创建 /etc/nginx/vhost/(上面include指定的地方) 文件夹
进入文件夹创建demo.conf、 demo2.conf文件

子配置1(demo.conf)
server {  # server参数下
        listen       80;  # 指定默认端口
        server_name  www.demo.com;  # 域名1
        location / {
            root /usr/share/nginx/demo/;  # 这表示读取配置文件所在目录下的index文件;
            index index.html index.htm;
        }
    }
子配置2(demo2.conf)
    server {  # server参数下
        listen       80;  # 指定默认端口
        server_name  cms.demo.com;  # 域名2
        charset utf-8;

        location / {
            root /usr/share/nginx/demo2/;  # 这表示读取配置文件所在目录下的index文件;
            try_files $uri $uri/ /index.html;
            index index.html index.htm;
        }
        #这里配置前端对应的后台服务
        location /prod-api/ {  
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header REMOTE-HOST $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass http://127.0.0.1:8080/;
         }
         #这是阿里云代理配置,不需要可忽略
        location ^~ https://XXXXX.oss-cn-hangzhou.aliyuncs.com/static/ {
            proxy_pass http://127.0.0.1:3333;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_hide_header X-Powered-By;
            proxy_set_header HOST $http_host;
            add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        }
    }

你可能感兴趣的:(杂,nginx,前端,运维)