Nginx配置Web项目(多页面应用,单页面应用)

时间:2023-03-09 22:05:03
Nginx配置Web项目(多页面应用,单页面应用)

目前前端项目 可分两种: 多页面应用,单页面应用。

单页面应用 入口是一个html文件,页面路由由js控制,动态往html页面插入DOM。

多页面应用 是由多个html文件组成,浏览器访问的是对应服务器的html文件。

多页面应用

目录结构

.
├── README.md
├── html
├── index.html
└── project.html
└── img
└── bg.jpg

上面这种情况 index.html 不在根目录下,nginx.conf 需要配置更加准确。

nginx配置

先来看一个有问题的nginx配置,因为做了太多的资源适配,会导致页面内资源访问或页面跳转有问题。

有问题的nginx配置

server {
listen 443 ssl;
server_name www.whosmeya.com;
ssl on;
ssl_certificate 1_www.whosmeya.com_bundle.crt;
ssl_certificate_key 2_www.whosmeya.com.key; location / {
root /root/libs/landing-page/;
try_files $uri $uri/index.html $uri.html @fallback;
} location @fallback {
root /root/libs/landing-page/;
rewrite .* /html/index.html break;
}
}

问题解析:

如果路径正确,没问题。

如果路径错误,会将资源定位到/html/index.html,且路径不跳转。

问题是如果/html/index.html用了相对路径获取资源或跳转,就会获取不到或跳转不过去。

例如:

访问 https://www.whosmeya.com/a/b 也能定位到资源 /html/index.html

页面内有个a链接 href="./project.html", 愿意是跳转/html/project.html,但在https://www.whosmeya.com/a/b下,会被跳转到https://www.whosmeya.com/a/project.html,然后没有对应资源,也会被定位到 /html/index.html

调整后的nginx配置

针对上面问题,需要针对多页面应用对nginx配置做修改:

server {
listen 443 ssl;
server_name www.whosmeya.com;
ssl on;
ssl_certificate 1_www.whosmeya.com_bundle.crt;
ssl_certificate_key 2_www.whosmeya.com.key; location / {
root /root/libs/landing-page/;
try_files $uri $uri.html @fallback;
} location @fallback {
root /root/libs/landing-page/;
rewrite .* /html/index.html redirect;
}
}

改动点

try_files $uri $uri/index.html $uri.html @fallback; -> try_files $uri $uri.html @fallback;

rewrite .* /html/index.html break; -> rewrite .* /html/index.html redirect;

这样会 直接找 $uri 或者 $uri.html, 找不到会重定向到 首页/html/index.html

补充:

rewrite最后一项参数

参数 说明
last 本条规则匹配完成后继续向下匹配新的location URI规则
break 本条规则匹配完成后终止,不在匹配任何规则
redirect 返回302临时重定向
permanent 返回301永久重定向

单页面应用

目录结构

.
├── asset-manifest.json
├── favicon.ico
├── index.html
├── manifest.json
├── precache-manifest.e641bb60bd40b24c7a13e1d60c2a5baa.js
├── service-worker.js
└── static
├── css
│   ├── main.2cce8147.chunk.css
│   └── main.2cce8147.chunk.css.map
├── js
│   ├── 2.b41502e9.chunk.js
│   ├── 2.b41502e9.chunk.js.map
│   ├── main.05bebd98.chunk.js
│   ├── main.05bebd98.chunk.js.map
│   ├── runtime~main.a8a9905a.js
│   └── runtime~main.a8a9905a.js.map
└── media
└── logo.5d5d9eef.svg

nginx配置

server {
listen 80;
server_name react.whosmeya.com; location / {
root /root/libs/whosmeya-react/;
try_files $uri @fallback;
} location @fallback {
root /root/libs/whosmeya-react/;
rewrite .* /index.html break;
}
}

单页面应用 配置思路是:

服务器收到的所有访问,能访问到就返回资源,访问不到就返回index.html。

fallback必须要设置,不然刷新页面会404。

rewrite要使用break,不需要redirect路由重定向,因为访问资源都是基于根目录 / 。