Skip to content

网络应用中经常会遇到1台服务器起多个应用在不同端口的情况

1、申请二级域名

从域名服务商那里,找到主域名,点解析,然后输入个二级域名name,指向服务器,一般来说会自动帮你配置DNS

2、安装nginx

看上一篇

3、配置主域名

想配置二级域名就得先配置个主域名www,详情参考上一篇

4、nginx配置子域名

server {
    # listen       80 default_server;
    # listen       [::]:80 default_server;
    listen       80;
    server_name  www.wulisensen.com;
    root         /home/www/;
    index  index.html;
    # try_files $uri /cache.php ;

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

    location / {
        index  index.html;
    }

    location /manage {
        index  index.html;
    }

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

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

server {
    listen       80;
    server_name  wordpress.wulisensen.com;
    proxy_set_header Host $host:8000;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    location / {
        proxy_pass       http://127.0.0.1:8000;
    }
}

上面的是我的主域名配置,下面是二级域名配置。

注意 proxy_set_header Host $host:8000; 要把端口号带上,不然会出现wordpress.wulisensen.com 被nginx 301 转发到 wordpress.wulisensen.com:8000 的情况,前端看到就很尴尬了。

5、给SPA项目做配置

server {
    listen       80;
    server_name  www.wulisensen.com;

    #charset koi8-r;

    access_log  /data/logs/nginx/localhost.access.log  main;

    location / {
        root         /home/www/;
        try_files $uri $uri/ @router;#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
        index  index.html;
    }
    #对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
    #因此需要rewrite到index.html中,然后交给路由在处理请求资源
    location @router {
        rewrite ^.*$ /index.html last;
    }

}