nginx重定向到尾部斜杠并替换索引.php(如果文件和文件夹不存在)



我想将所有URL重定向,而没有Trailin Slashes,将301重定向到同一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带有尾随slash。

我也尝试使用代码:

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进行任何重定向。

我如何使两个重定向到落后斜线和索引。php?

我找到了工作解决方案。它使用不良练习(如果是邪恶),但它只是工作代码。因此,如果有的话,我将感谢您的决定。

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;
}

相关内容

最新更新