nginx location 正则配置多个路由模块
# 示例nginx配置文件,其中包含两个location块,分别匹配以/post和/user开头的URL路径:
server {
listen 80;
server_name example.com;
location ~ ^/post/(.*)$ {
# 匹配以/post开头的URL路径
# $1 代表正则表达式中的第一个捕获组,即(.*)匹配的内容
proxy_pass http://localhost:8000/posts/$1;
}
location ~ ^/user/(.*)$ {
# 匹配以/user开头的URL路径
# $1 代表正则表达式中的第一个捕获组,即(.*)匹配的内容
proxy_pass http://localhost:8000/users/$1;
}
}
上述示例中
- 第一个location块匹配以**/post**开头的URL路径,并将请求转发到http://localhost:8000/posts/路径下
- 第二个location块匹配以**/user**开头的URL路径,并将请求转发到http://localhost:8000/users/路径下
nginx 一个 location 正则配置多个路由模块
示例 1
server {
listen 80;
server_name example.com;
location ~ ^/(post|user)(.*)$ {
# 匹配以 /post 或者 /user 开头的URL路径
# $1 代表正则表达式中的第一个捕获组,即(.*)匹配的内容
proxy_pass http://localhost:8000/posts/$1;
}
}
上述示例中
- 使用了正则表达式来匹配以
/user/
或/post
开头的路径,并且后面可以跟任意字符 - 其中
~
表示使用正则表达式匹配,^
表示匹配行的开头,()
表示分组,|
表示或,.*
表示匹配任意字符 - 这个正则表达式可以匹配类似于
/user/123
或/post/abc/def
这样的路径 - 另外,根据引用中的规则,
location ~,~*
的正则顺序是按照配置文件中出现的顺序进行匹配的 - 因此在配置文件中应该按照需要的顺序编写正则表达式
示例 2
server {
listen 80;
server_name kiki.lic.com;
charset utf-8;
access_log /var/log/nginx/www.lic.com-access.log;
location ~ /(post|article|news) {
rewrite (.+) http://www.lic.com/kiki$1 permanent;
}
location / {
root html;
index index.html index.htm;
}
}
上述配置中
- 使用了正则表达式
/(post|article|news)
来匹配三个路由模块 - 然后使用
rewrite
指令将匹配到的URL重定向到http://www.lic.com/kiki
下 - 其中,
$1
表示正则表达式中第一个括号内匹配到的内容,即路由模块的名称