我正在尝试将 location 处的所有流量传递^/[a-z0-9]{24}$
到不同根目录下的 index.html。我的配置设置如下:
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
root /Users/me/sites/store_front/static;
index index.html;
try_files $uri $uri/ $uri.html =404;
location ~ "^/[a-z0-9]{24}$" {
alias /Users/me/web_app/static;
try_files $uri index.html;
}
}
由于某种原因,当我 curl 此 url 时,我得到了 404:
$ curl -I https://example.com/55c898e7faa137f42409d403
HTTP/1.1 404 Not Found
Server: nginx/1.8.0
Content-Type: text/html; charset=UTF-8
Content-Length: 168
Connection: keep-alive
有谁知道如何使这个别名起作用?
更新:
需要注意的是,我需要 index.html 中的所有相对 URL 才能正确加载:
<link href="/styles/main.css" rel="stylesheet" type="text/css"
<script src="/javascript/main.js"></script>
这些文件实际上存在于web_app
目录中,但 nginx 尝试从store_front
谢谢
答案1
指向^/[a-z0-9]{24}$
很index.html
容易。资源文件/styles/main.css
需要/javascript/main.js
有唯一的 URI,否则nginx
不知道要提供哪些文件。
如果store_front 也使用/styles
和/javascript
前缀,则需要隔离单个文件:
location = /styles/main.css {
root /Users/me/web_app/static;
}
location = /javascript/main.js {
root /Users/me/web_app/static;
}
location ~ "^/[a-z0-9]{24}" {
root /Users/me/web_app/static;
rewrite ^ /index.html break;
}
如果/styles
、/javascript
和^/[a-z0-9]{24}$
URI 都是唯一的,则可以将上述内容合并到一个位置:
location ~ "^/([a-z0-9]{24}|styles|javascript)" {
root /Users/me/web_app/static;
rewrite "^/[a-z0-9]{24}$" /index.html break;
}
甚至:
location ~ "^/([a-z0-9]{24}|styles/main.css|javascript/main.js)" {
root /Users/me/web_app/static;
rewrite "^/[a-z0-9]{24}$" /index.html break;
}