Home nginx redirect to trailing slashes and substitude to index.php (if files and folders don't exists)
Reply: 1

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

zen
1#
zen Published in 2017-12-05 12:12:35Z

I want to redirect all urls without trailin slashes with 301 redirect to same urls with trailing slashes. Also I want to substitude all urls to index.php, if its not a folder or file.

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.

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?

zen
2#
zen Reply to 2017-12-05 12:30:27Z

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;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.425014 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO