Nginx 常用配置避坑与说明:root/alias、路径透传与 SPA 部署

10 天前
/
1

Nginx 常用配置避坑与说明:root/alias、路径透传与 SPA 部署

最近使用AI Agent, 框架开发web应用。然而设计数据库或前后端交互时,还需自行设计后端。当然过于跨域等老生常谈的问题不用过多赘述,因为Nginx解决了大部分。在开发过程中总结一些关于Nginx配置踩坑并额外补充的一些前端知识。

一个简单的配置

## web
    location /tb/ {
    alias D:/Projects/xxx/dist/;
    index index.html;
    try_files $uri $uri/ /tallybook/index.html;
    }
## api
    location /tbapi/ {
        proxy_pass http://127.0.0.1:8000/;
        proxy_redirect off;
    }

root 与 alias

localtion 模块中用来指定映射服务器静态资源文件的命令

  • root 是追加:它把请求的 URL 拼接到 root 指定的路径后面。
  • alias 是替换:它用 alias 指定的路径 替换掉 location 匹配的部分。

当浏览器访问:*http://site.com/images/cat.jpg 时*

location /images/ {
    root /var/www/html;
}

→ /var/www/html/images/cat.jpg

location /images/ {
    alias /var/www/html/;
}

/var/www/html/cat.jpg

注意:如果 location 后面有 /(例如 /images/),那么 alias 后面必须也要加 /。

proxy_pass 反向代理的路径透传

对于nginx设置

location /downloader/data/ {
    proxy_pass http://127.0.0.1:8000/;
locationproxy_pass后端收到的 URI
/downloader/datahttp://127.0.0.1:8000/downloader/data/file.txt
/downloader/data/http://127.0.0.1:8000/downloader/data/file.txt
/downloader/data/http://127.0.0.1:8000//file.txt
/downloader/datahttp://127.0.0.1:8000/未定义/危险

如果设置了autoindex on; location 建议以 / 结尾

注意,此时只会路由到/downloader/data/

🕳 python http.server

最好的debug方式就是在 do_GET中打印地址


def do_GET(self):
    print(self.path)
    # ...
    super().do_GET()

启用 http.server 需要注意的坑
场景:将http.server作为静态资源服务器,指定资源目录

如果希望指定目录. 则需要在python后端重写path这种方法在需要修改目录的情况下最方便。

# 将 Nginx 传来的虚拟路径替换为本地实际目录
self.path = self.path.replace('/downloader/data', f'/{DIRECTORY}')
# 指定 http.server 访问的目录
# self.path = f'/{DIRECTORY}' + self.path

try_files 单页应用(SPA)的部署策略

try_files $uri $uri/ /index.html;

为什么这样写:

现代 SPA(单页应用)

现在的前端框架(如 Vue/React),整个网站其实只有一个 HTML 文件(通常是 index.html)。页面的切换(路由)是由浏览器里的 JavaScript 控制的,而不是服务器。

问题来了:

  1. 用户访问首页 http://site.com/ -> Nginx 返回 index.html -> JS 加载 -> 此时用户点击按钮跳转到 /user/profile。
    • 注意:这时候浏览器地址栏变了,但浏览器并没有向 Nginx 发送请求,是 JS 把页面内容变了。一切正常。
  2. 但是! 用户在 /user/profile 这个页面,按了一下 F5 刷新
  3. 浏览器向 Nginx 发送请求:GET /user/profile。
  4. Nginx 傻眼了:我去哪里找 /user/profile 这个文件?根目录下根本没有 user 文件夹,更没有 profile 文件。
  5. Nginx 默认行为:直接报 404 错误

作用 (三步走)

先尝试访问路由文件→ 访问目录 + index/html(如果存在)→ 指定的html (兜底)

一种优雅的“静态资源优先,应用入口兜底” 的设计模式

使用社交账号登录

  • Loading...
  • Loading...
  • Loading...
  • Loading...
  • Loading...