侧边栏壁纸
博主头像
xuesheng博主等级

分享web知识,学习就是取悦自己!

  • 累计撰写 118 篇文章
  • 累计创建 14 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录

nginx 配置 同一域名端口下,根据URL 导向不同的项目目录

xuesheng
2022-09-28 / 1 评论 / 0 点赞 / 569 阅读 / 682 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-09-28,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

我们现在拥有2个项目。但是只有一个域名,通过nginx配置来实现以下url导向不同的项目。

后台管理台:{域名}/admin

用户客户端:{域名}/client

server {
    listen 8888;
    server_name ****.*****.com;
    root /home/work/***/static/client;
    index index.html;
    autoindex on;
    charset   utf-8;

    location ~ /(system|car)/ {
        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_pass http://192.168.1.1:3000;
    }

    #配置Nginx动静分离,定义的静态页面直接从Nginx发布目录读取。
    location /admin {
        alias /home/work/****/static/admin/;
        expires  1d;
        index index.html;
    autoindex on;
    }

    access_log /home/work/****/logs/static_admin_ng_access.log;

    location /api/ {
        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_pass http://192.168.1.1:3000;
    }
    #配置Nginx动静分离,定义的静态页面直接从Nginx发布目录读取。
    location /client {
        alias /home/work/****/static/client/;
        #expires 为用户信息的缓存时间。1d为一天
        expires  1d;
        index index.html;
    autoindex on;
    }
    access_log /home/work/****/logs/static_client_ng_access.log;

}

在配置这个的时候,遇到一个坑,就是alias 和root 的区别,导致获取的静态文件的获取的路径不对,一直报404;郁闷的很;

在配置ng 的location 的生活;一般不要加后面的斜杆;然后加上autoindex on; 自动首页;这样就会自动跳转到首页了;

alias 和 root 的区别; root 的话;location 中的地址会拼接到root后面;alias就直接代替后面的东西;

如:

location /admin {
	root  /admin/res/;
	index html.html;
	autoindex no;
}
location /admin {
	alias /admin/res/;
	index html.html;
	autoindex no;
}

访问地址:localhost:8888/admin/res/app.js;

root实际访问的地址就是: localhost:8888/admin/res/admin/res/app.js

也就是说这个实际访问的地址 ./admin/res/admin/res/app.js ;这样根本找不到文件;

alias 实际的访问地址就是: localhost:8888/admin/res/app.js;

访问的地址是 ./admin/res/app.js

location /admin/{
	root  /admin/res/;
	index html.html;
	autoindex no;
}

上面这种配置 localhost:8888/admin 是不能跳转到首页的;
需要加上斜杆 localhost:8888/admin/ 才能跳转到首页

location /admin{
      root  /admin/res/;
      index html.html;
      autoindex no;
}

这种访问的时候: localhost:8888/admin 这样就可以直接访问了;

配置服务器代理:

location /api/ {
    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_pass http://192.168.1.1:3000;
}

一定要填写

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_pass http://192.168.1.1:3000;

这4项了;

现在这样访问的地址就是 http://192.168.1.1:3000/api/...........;

0
博主关闭了所有页面的评论