大网数据广告活动
服务器运维问答

use "rewrite" and "try_files" together [Nginx]

· 52CE 我爱测

I removed the ".php" suffix at the end of the PHP files on the Nginx server with the following code, but this time I cannot send some data to the server. try_files $uri/ $uri.html $uri.php$is_args$query_string; Some links on the …

问题原文

原帖链接 · Emre6 · CC BY-SA 4.0

I removed the ".php" suffix at the end of the PHP files on the Nginx server with the following code, but this time I cannot send some data to the server.

try_files $uri/ $uri.html $uri.php$is_args$query_string;

Some links on the site are sent with Ajax, and the ".php" extension is not available at the end of these links. E.g; https://panel.example.com/app/controller/ajax/collect

For example, when I want to access the "/collect" file that I want to access via Ajax or directly, I get the error "File not found". Because I do "rewrite" with the code below and provide a clean URL.

rewrite ^/([^/]+)/([^/]+)?$ /index.php?cmd=$1&scd=$2 last;
rewrite ^/([^/]+)/?$ /index.php?cmd=$1 last;

Sample link: https://panel.example.com/[details|cat|profile]/[subPages(productID, username..)]

As a result, the above codes are correct and working, but not working at the same time together. How can I run these two codes at the same time?

Full Nginx vHost File

社区高分解答

原帖链接 · Tero Kilkanen · CC BY-SA 4.0

You could try following approach:

location ~ ^/(?<cmd>[^/]+)/(?<scd>[^/]+) {
    try_files /index.php?cmd=$cmd&scd=$scd =404;
}

location ~ ^/(?<cmd>[^/]+)/ {
    try_files /index.php?cmd=$cmd =404;
}

location / {
    try_files $uri/ $uri.html $uri.php$is_args$args;
}

We use nginx location matching algorithm here to first check matching of URL to regular expressions and then taking appropriate action for that URL.

I am using named captures here ?<cmd> to make variable names more clear.

Also, the ?$ part at end of regular expression is removed, since it makes no difference. Both ?$ and empty match any string.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-12-31)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。