【发布时间】:2018-07-19 04:48:37
【问题描述】:
我有一个nginx version: nginx/1.10.3 (Ubuntu) 在Ubuntu 16.04.2 LTS 上运行。
我使用nginx 提供静态文件,webpack 生成的捆绑包,但这无关紧要。
我想要实现的是:
在example.com 我想为/home/bundles/main/index.html 服务。我可以做到。
在projects.example.com/project_1 我想服务/home/bundles/project_1/index.html。
在projects.example.com/project_2 我想服务/home/bundles/project_2/index.html。
最后两个,我做不到。当我转到 projects.example.com/project_1 或 projects.example.com/project_2 时,我会看到默认的 nginx 页面。
为了让事情更混乱,/etc/nginx/sites-enabled/default 被完全注释掉了。
此外,如果在projects.example.com 的location 块中,我将project_1 替换为/,我将获得该特定项目的服务,但我将无法为其他项目服务。
下面,我将向你展示我的 nginx 配置
server {
listen 80;
server_name example.com;
location / {
root /home/bundles/main;
try_files $uri /index.html;
}
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name example.com;
location / {
root /home/bundles/main;
try_files $uri /index.html;
}
ssl_certificate ...
ssl_certificate_key ...
}
server {
listen 80;
server_name projects.example.com;
location /project_1 {
root /home/bundles/project_1;
try_files $uri /index.html;
}
location /project_2 {
root /home/bundles/project_2;
try_files $uri /index.html;
}
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name projects.example.com;
location /project_1 {
root /home/bundles/project_1;
try_files $uri /index.html;
}
location /project_2 {
root /home/bundles/project_2;
try_files $uri /index.html;
}
ssl_certificate ...
ssl_certificate_key ...
}
感谢您的帮助!
编辑
我的答案
我找到的解决方案是将root 更改为alias。
server {
listen 80;
server_name example.com;
location / {
root /home/bundles/main;
try_files $uri /index.html;
}
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name example.com;
location / {
root /home/bundles/main;
try_files $uri /index.html;
}
ssl_certificate ...
ssl_certificate_key ...
}
server {
listen 80;
server_name projects.example.com;
location /project_1 {
alias /home/bundles/project_1;
index index.html;
}
location /project_2 {
alias /home/bundles/project_2;
index index.html;
}
if ($scheme != "https") {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name projects.example.com;
location /project_1 {
alias /home/bundles/project_1;
index index.html;
}
location /project_2 {
alias /home/bundles/project_2;
index index.html;
}
ssl_certificate ...
ssl_certificate_key ...
}
解决方案基于这两个答案。第一个answer 展示了如何解决问题,第二个answer 解释了为什么alias 有效而root 无效。
引用@treecoder
在 root 指令的情况下,完整路径被附加到包含位置部分的根,而在别名指令的情况下,只有不包括位置部分的路径部分被附加到别名。
在我的特殊情况下,这会翻译成这样;
使用root,nginx 尝试访问的路径将是/home/bundles/project_1/project_1。
使用alias,它会访问正确的路径/home/bundles/project_1。
回溯一级,例如,说:
root /home/bundles/ 也不是一个真正的选择。那是因为我的项目实际上并没有被称为project_1 和project_2。实际结构与此更相似。
在/bundles 我有目录project_a 和project_b。我想将project_1 路由到project_a 目录,将project_2 路由到project_b 目录。
这就是我使用alias的原因。
我希望这会有所帮助。
【问题讨论】:
标签: nginx configuration server configuration-files nginx-location