繁体   English   中英

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

[英]How to route all requests to index.php, route non-existing files to error page, use pretty URLs, and add trailing slashes?

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

  • 将所有传入请求路由到index.php
  • 将不存在的文件路由到错误页面
  • 将网址重写为漂亮的版本(不带.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} !(.*)/$

我究竟做错了什么? 我添加了评论以描述我认为应该发生的情况,因此如果需要,请纠正我。

这是您应该做的:

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]

暂无
暂无

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

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