【问题标题】:Call to PHP page served by nginx without using the file extension调用 nginx 提供的 PHP 页面而不使用文件扩展名
【发布时间】:2020-09-16 05:12:38
【问题描述】:

我确信这是一个非常简单的答案,但我似乎无法破解它。我对 nginx 也很陌生,但对 apache2 非常了解。我在 Ubuntu 上运行 nginx 并尝试满足这两个请求:

  1. 当 URI 调用 filename 时,让 nginx 为 filename.php 提供服务
    1. 调用 http://example.org/bob 将服务于 http://example.org/bob.php,但仍会在浏览器 URL 中显示 http://example.org/bob
  2. 请求文件夹时,URL 中不显示“索引”
    1. 调用http://example.org/jack/ 将提供http://example.org/jack/index.phphttp://example.org/jack/ 仍显示在URL 中(而不是http://example.org/jack/index

我目前的配置是:

server {
    listen 80;
    root /var/www/html;
    index index.php;

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

    location @php {
        try_files $uri.php =404;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi.conf;
    }

    rewrite ^/(.*)\.php$ /$1 redirect;

    location ~ /\.ht {
        deny all;
    }
}

我觉得我真的很接近了,要求 (1) 完美无缺,但我似乎找不到正确的配置来满足要求 (2)。

如果有帮助,这是在 Apache2 中工作的配置,启用了 mod_rewrite 模块:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d       # if a folder isn't called ...
RewriteCond %{REQUEST_FILENAME}.php -f    # but a php file is ...
RewriteRule ^(.*)$ $1.php                 # take the basename, add .php then call that

【问题讨论】:

    标签: nginx redirect mod-rewrite


    【解决方案1】:

    看到这个可以帮助你启用 Apache2 重写规则到 nginx 规则:

    https://www.nginx.com/blog/converting-apache-to-nginx-rewrite-rules/

    location / {
      if (!-e $request_filename){
        rewrite ^(.*)$ /$1.php;
      }
    }
    

    【讨论】:

    • 有趣的是,该博客与 this article 来自同一站点,关于 not 在 nginx 的配置中使用 if 语句
    猜你喜欢
    • 2016-03-08
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 2015-03-26
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多