【问题标题】:nginx redirect to trailing slashes and substitude to index.php (if files and folders don't exists)nginx 重定向到尾部斜杠并替换为 index.php(如果文件和文件夹不存在)
【发布时间】:2017-12-05 12:12:35
【问题描述】:

我想用 301 重定向所有不带斜杠的 url 重定向到带有斜杠的相同 url。如果不是文件夹或文件,我也想将所有 url 替换为 index.php。

我试图用以下代码做到这一点:

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

location ~* .*[^/]$ {
  try_files $uri $uri/ permanent;
}

location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.0-mysite-fpm.sock;
  fastcgi_read_timeout 300;
}

第一个位置单独工作完美,但这些位置不能一起工作。它通常返回文件和文件夹,但是当请求没有斜杠的url时,nginx返回500错误,并且只返回文件index.php下载,当url带有斜杠时。

我也尝试用代码来实现:

location / {
    try_files $uri $uri/ @addslash /index.php$is_args$args;
}
location @addslash {
    rewrite ^(.+[^/])$ $1/ permanent;
}
location ~ \.php$ {
  include snippets/fastcgi-php.conf;
  fastcgi_pass unix:/run/php/php7.0-mysite-fpm.sock;
  fastcgi_read_timeout 300;
}

但它可以在没有任何来自 url 的重定向的情况下工作,而无需尾部斜杠。

如何使重定向到斜杠和替换到 index.php?

【问题讨论】:

    标签: php redirect nginx


    【解决方案1】:

    我找到了可行的解决方案。它使用了不好的做法(如果是邪恶的),但它只是有效的代码。因此,如果任何人能表现出更好的工作决定,我将不胜感激。

    set $my_var 0;
    if (-f $request_filename) {
      set $my_var 1;
    }
    if (-d $request_filename) {
      set $my_var 1;
    }
    if (-d $request_filename) {
      set $my_var 1;
    }
    if ($request_uri ~ "^.*/market/cart$") {
      set $my_var 1;
    }
    if ($request_uri ~ "^.*/market/order/accept$") {
      set $my_var 1;
    }
    if ($request_uri ~ "^.*/market/order/status$") {
      set $my_var 1;
    }
    if ($request_uri ~* "(.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif)$") {
      set $my_var 1;
    }
    
    if ($my_var = 0) {
      rewrite ^(.*[^/])$ $1/ permanent;
    }
    
    if ($request_uri ~* "^(.*/)index\.php$") {
      return 301 $1;
    }
    
    
    location ~* (.+)\.(?:\d+)\.(js|css|png|jpg|jpeg|gif)$ {
      try_files $uri $1.$2;
    }
    
    location / {
      try_files $uri $uri/ /index.php$is_args$args;
    }
    
    location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass unix:/run/php/php7.0-newstom-fpm.sock;
      fastcgi_read_timeout 300;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-28
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      相关资源
      最近更新 更多