【问题标题】:Nginx redirect with/without php extensionNginx 重定向带/不带 php 扩展
【发布时间】:2016-02-03 08:05:02
【问题描述】:

我正在构建一个 NGINX 虚拟主机,它应该:

  • 将以 .php 结尾的页面重定向到不带扩展名的版本(301 重定向)
  • 正确处理不以 .php 结尾的 URL,将它们传递给 FASTCGI 以执行 php

我的问题是这实际上会创建一个无限重定向循环。我在这里错过了什么?

server {
  server_name ~^my\.domain\.com$;

  listen 80;
  root /path/to/root;

  error_page 404 /404.php;

  location ~ \.php$ {
    rewrite ^(.*)\.php$ $1 permanent;
    break;
  }

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

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

  location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        # rest of fastcgi configuration...
  }
}

【问题讨论】:

    标签: php redirect nginx


    【解决方案1】:

    首先,您不能有两个 location ~ \.php$ 块。解决方案是在命名位置本身内处理fastcgi_pass,并避免内部重写为.php。像这样的:

    location / {
        try_files     $uri @php;
    }
    location @php {
        try_files     $uri.php $uri/index.php =404;
    
        include       fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass  ...;
    }
    location ~* ^(.*)\.php$ { 
        return 301 $1; 
    }
    

    请注意,不再需要 index 指令和 $uri/ 元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 2021-11-30
      • 2022-10-17
      • 1970-01-01
      相关资源
      最近更新 更多