【问题标题】:Redirect all url in directory to single php in nginx将目录中的所有url重定向到nginx中的单个php
【发布时间】:2026-01-19 08:05:01
【问题描述】:

我想要一个 php 脚本来处理对我的 /blog 目录的所有传入请求。 php 脚本检查 url 是否存在 SQL 记录(即 www.example.com/blog/example_article)。如果找到一条记录,它将提供相应的页面数据。如果 url 没有记录(即 www.example.com/blog/nothing_here),它会重定向到 404。

为此我需要 nginx 中的重写规则。

我当前的配置:

    root /usr/share/nginx/html/example/;
    index index.php;

    server_name example.com www.example.com;

    location / {
            try_files $uri $uri/ @extensionless-php;
    }

    location /blog {
            rewrite ?; // here i need a rewrite rule
    }

    location /uploads {
            deny all;
    }

    error_page 404 /templates/404.php;

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
            fastcgi_intercept_errors on;
    }

    location @extensionless-php {
            rewrite ^(.*)$ $1.php last;
    }

请注意,我使用的是无扩展名 URL。

【问题讨论】:

标签: php url nginx url-rewriting


【解决方案1】:

答案:

location /blog {
    index article.php;
    rewrite ^/blog/(.*)$ /blog/article.php?slug=$1;
}

【讨论】:

  • 虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,纯代码的答案没有用处。
最近更新 更多