nginx 配置文件
server {
listen 80;
server_name api.xxx.com;
root /mnt/try;
location / {
add_header Content-Type 'text/html; charset=utf-8';
#echo $uri;
try_files $uri @default;
}
location @default {
root /mnt/default;
}
}
server {
listen 80;
server_name api.xxx.com;
root /mnt/try;
location / {
add_header Content-Type 'text/html; charset=utf-8';
#echo $uri;
try_files $uri @default;
}
location @default {
root /mnt/default;
}
}
location @xxx 作用
location @xxx解释:定义一个location段,不能被外部请求所访问,只能用于nginx内部配置指令使用,比如 try_files、error_page。
$uri解释:URI代表资源的名称
浏览器访问 http://api.xxx.com/abc/index.html 时,当前的$uri值为/abc/index.html
可以通过编译nginx参数--add-module添加第三方echo模块打印$uri
try_files作用:
try_files会先尝试去/mnt/try目录下找abc目录下的index.html,如果有,直接返回,没有的话则跳转到@default部分(内部重定向)。
在default部分会去/mnt/default目录下找abc目录下的index.html,有,直接返回,没有就返回404错误。
try_files可以理解为实现rewrite的作用
bash
try_files $uri $uri/ /index.html; 这句话是Nginx服务器配置中的一条指令,用于设置处理请求的策略。
$uri:这是Nginx内置的一个变量,代表当前请求的URI,不包括参数部分。例如,如果请求的URL是http://example.com/user?id=1,那么$uri的值就是/user。
$uri/:尝试将请求作为目录处理,如果这个目录存在,Nginx会试图返回该目录下的默认文件(通常是index.html或index.htm)。
/index.html:如果前面的$uri和$uri/都无法找到对应的文件或目录,那么就返回/index.html文件。
因此,try_files $uri $uri/ /index.html; 的含义是:首先尝试按照请求的URI去寻找对应的文件,如果找不到,再尝试将请求作为目录处理,如果还是找不到,最后就返回/index.html文件。
这对于单页应用来说非常有用,因为无论用户请求的是什么URL,服务器都会返回同一个HTML文件(即index.html),然后由前端路由来决定显示哪个页面。
try_files $uri $uri/ /index.html; 这句话是Nginx服务器配置中的一条指令,用于设置处理请求的策略。
$uri:这是Nginx内置的一个变量,代表当前请求的URI,不包括参数部分。例如,如果请求的URL是http://example.com/user?id=1,那么$uri的值就是/user。
$uri/:尝试将请求作为目录处理,如果这个目录存在,Nginx会试图返回该目录下的默认文件(通常是index.html或index.htm)。
/index.html:如果前面的$uri和$uri/都无法找到对应的文件或目录,那么就返回/index.html文件。
因此,try_files $uri $uri/ /index.html; 的含义是:首先尝试按照请求的URI去寻找对应的文件,如果找不到,再尝试将请求作为目录处理,如果还是找不到,最后就返回/index.html文件。
这对于单页应用来说非常有用,因为无论用户请求的是什么URL,服务器都会返回同一个HTML文件(即index.html),然后由前端路由来决定显示哪个页面。