Nginxlocalhost 路由匹配规则详细说明以及案例
参考资料
Nginx 的 localhost 路由匹配规则主要通过 server 块和 location 块来定义。以下是详细说明和案例:
1. server 块
server 块用于定义一个虚拟主机,通常包含监听端口和服务器名称(如 localhost)。
server {
listen 80;
server_name localhost;
location / {
root /var/www/html;
index index.html;
}
}2. location 块
location 块用于定义请求的 URI 匹配规则,并指定如何处理这些请求。
2.1 精确匹配 (=)
精确匹配要求请求的 URI 完全匹配指定的路径。
location = /exact {
return 200 "This is an exact match";
}2.2 前缀匹配 (^~)
前缀匹配优先于正则表达式匹配,通常用于静态文件路径。
location ^~ /static/ {
root /var/www/static;
}2.3 正则表达式匹配 (~ 和 ~*)
~表示区分大小写的正则表达式匹配。~*表示不区分大小写的正则表达式匹配。
location ~ \.php$ {
proxy_pass http://php_backend;
}
location ~* \.(jpg|jpeg|png|gif)$ {
root /var/www/images;
}2.4 通用匹配 (/)
通用匹配会匹配所有请求,通常用于默认处理。
location / {
try_files $uri $uri/ =404;
}3. 优先级
Nginx 的 location 匹配优先级如下:
精确匹配 (
=)前缀匹配 (
^~)正则表达式匹配 (
~和~*)通用匹配 (
/)
4. 案例
以下是一个完整的 nginx.conf 示例:
server {
listen 80;
server_name localhost;
# 精确匹配
location = /exact {
return 200 "This is an exact match";
}
# 前缀匹配
location ^~ /static/ {
root /var/www/static;
}
# 正则表达式匹配(区分大小写)
location ~ \.php$ {
proxy_pass http://php_backend;
}
# 正则表达式匹配(不区分大小写)
location ~* \.(jpg|jpeg|png|gif)$ {
root /var/www/images;
}
# 通用匹配
location / {
try_files $uri $uri/ =404;
}
}5. 测试
启动 Nginx 后,可以通过以下 URL 测试:
http://localhost/exact返回 "This is an exact match"http://localhost/static/style.css返回/var/www/static/style.csshttp://localhost/index.php转发到http://php_backendhttp://localhost/image.jpg返回/var/www/images/image.jpghttp://localhost/other返回 404 错误
通过这些规则,可以灵活地配置 Nginx 的路由匹配和处理逻辑。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . 宝塔 | 西里网》 -- 发布时间:2025-03-29
本页链接:https://bt.ciilii.com/show/news-63.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
