简体   繁体   中英

How to redirect pages with php extension in GRAV

I created a new web site using Grav. The old site has pages that had to be accessed using urls ending .php The url /somefolder/somepage.php just gives me "File not found". It does NOT lead me to the built-in Grav error page.

I disabled the error plugin of Grav so it does not get in the way.

How do I rewrite /somefolder/somepage.php to /somefolder/somepage
Also, how can I redirect any 404 error to the home page?
The error is handled by:

/var/www/grav-admin/system/src/Grav/Common/Processors/PagesProcessor.php

if (!$page->routable()) {
            // If no page found, fire event
            $event = $this->container->fireEvent('onPageNotFound');

            if (isset($event->page)) {
                unset ($this->container['page']);
                $this->container['page'] = $event->page;
            } else {
                throw new \RuntimeException('Page Not Found', 404);
            }
        }

How can I replace the line "throw new \\RuntimeException('Page Not Found', 404);" with an instruction to redirect to the home page?

The above error is only caught for urls NOT ending in .php
urls ending in .php are not handled by Grav, so I guess it's the web server handing those errors. The web server is nginx/1.11.9.
I tried adding the lines below to my nginx.conf but this did not resolve the problem.

error_page 404 = @foobar;

    location @foobar {
      rewrite  .*  / permanent;
    }

I would handle both of your problems on server-side.

How do I rewrite /somefolder/somepage.php to /somefolder/somepage

I would do something like :

location ~ \.php$ {
  if (!-f $request_filename) {
      rewrite ^(.*)\.php$ $1.html permanent;
  }
}

Which mean : for every php file requested, remove the php and replace .php by .html.

Also, how can I redirect any 404 error to the home page?

This problem may occur because of 2 common things :

  • http header problem : you don't change the http header in your redirect here so you still serve a 404. Before checking if the location exists, the server searches for the http code status. Here, it remains 404.
  • you may use fastcgi_intercept_errors on;

For that problem, I would use this piece of code :

server {
  ...
  index index.html index.php
  error_page 404 = @hpredirect;
  ...
  location @hpredirect {
    return 301 /;
  }
}

Hope it helps !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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