Nginxlocalhost 路由匹配规则详细说明以及案例
参考资料
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 的路由匹配和处理逻辑。

