简体   繁体   English

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

[英]nginx redirect to trailing slashes and substitude to index.php (if files and folders don't exists)

I want to redirect all urls without trailin slashes with 301 redirect to same urls with trailing slashes. 我想用301重定向所有没有结尾斜杠的URL到带有结尾斜杠的相同URL。 Also I want to substitude all urls to index.php, if its not a folder or file. 另外,如果不是文件夹或文件,我想将所有URL都归并到index.php。

I tried to make this with following code: 我试图用下面的代码做到这一点:

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

First location working perfect alone, but this locations don't work together. 第一个位置可以单独正常工作,但是此位置不能一起工作。 It return normally files and folders, but when request urls without slash nginx returns 500 error, and just return file index.php to download, when url with trailing slash. 它通常返回文件和文件夹,但是当请求的URL不带斜杠时,nginx返回500错误,并且仅返回文件index.php进行下载,而URL带有斜杠。

Also I tried to make it with code: 我也尝试用代码来做到这一点:

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

But it works without any redirections from urls without trailing slashes. 但它可以正常工作,而不会在没有尾随斜杠的情况下对网址进行任何重定向。

How can I make working both redirects to trailing slash and substitude to index.php? 如何使两个重定向都重定向到尾部斜杠,然后再替换到index.php?

I found working solution. 我找到了可行的解决方案。 It uses bad practice (if is evil), but it's only working code. 它使用了错误的做法(如果是邪恶的话),但这只是有效的代码。 So if any will show better workig decision, I will be grateful. 因此,如果有任何更好的决定,我将不胜感激。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM