如何将所有请求路由到index.php,将不存在的文件路由到错误页面,使用漂亮的URL,并添加尾部斜杠?

时间:2017-01-16 05:21:54

标签: php apache .htaccess mod-rewrite routes

如何在我的.htaccess文件中一起完成所有这些操作?

  • 将所有传入请求路由到index.php
  • 将不存在的文件路由到错误页面
  • 将URLS重写为漂亮的版本(不带.php)
  • 为SEO目的自动添加尾部斜杠

我已经知道如何单独进行这些操作,但是很难让他们一起工作。这是我到目前为止所得到的:

RewriteEngine on
RewriteBase /apps/louis/

#if file doesn't exist, try grabbing the .php version of it and continue on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [NC,N]

#if .php file doesn't exist, route to the index page with a 404 code and "error" param so index page knows to display error content
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?pageName=error [QSA,NC,R=404,L]

#if request name is not empty, route to the index page with a param of the page name so it knows which content to display
RewriteCond %{REQUEST_URI} !^$
RewriteRule ^(.*)$ index.php?pageName=$1 [QSA,NC,L]

#as long as the requested URL isn't an image or CSS file or script, tack on a trailing slash
RewriteCond %{REQUEST_URI} !\.(jpg|png|gif|css|js)$
RewriteCond %{REQUEST_URI} !(.*)/$

我做错了什么?我添加了评论来描述我认为应该发生的事情,所以如果需要请纠正我。

1 个答案:

答案 0 :(得分:0)

这是你应该做的:

RewriteEngine on
RewriteBase /apps/louis/

#as long as the requested URL isn't an image or CSS file or script, tack on a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]

#if file doesn't exist, try grabbing the .php version of it and continue on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

#if .php file doesn't exist, route to the index page with a 404 code and "error" param so index page knows to display error content
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?pageName=error [QSA,L]

# existing files are routed to index.php
RewriteCond %{REQUEST_URI} !\.(jpe?g|png|gif|css|js)$ [NC]
RewriteRule ^(?!index\.php)(.+)$ index.php?pageName=$1 [NC,QSA,L]