重写/重定向有关扩展名和斜杠的问题

时间:2011-09-12 02:19:24

标签: php apache .htaccess mod-rewrite redirect

我正在尝试从我的PHP页面制作好的,SEO友好的URL,但我一直遇到500内部错误,所以我被卡住了。这是纲要:

文件夹结构

  /    
    /index.php
       /about      <--Folder
       /about/index.php   
       /about/our-people.php   <--a subpage
       /services   <--Another folder
       /services/index.php
       /services/service1.php  <--another subpage

我希望它能够使URL不具有.php扩展名,但包含一个尾部斜杠。例如,“我们的人”页面将 www.example.com/about/our-people /

www.example.com/about/our-people.php或www.example.com/about/our-people(无尾随斜线)将转到 www.example.com/about/our-people /

我知道这个问题可能已被要求死亡,但我已经从Stackoverflow和其他地方尝试过很多例子。 Apache对我来说就像伏都教一样,有时它会做出神奇的事情,有时它只是不起作用。这是我到目前为止的代码:

#add www to non-www
RewriteCond %{HTTP_HOST} ^example.com [NC] 
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301] 

#Remove .PHP
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php [L]

#Add Slash
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.example.com/$1/ [L,R=301]

1 个答案:

答案 0 :(得分:0)

我会稍微改变一下。如果您对Apache不是很熟悉,那么我建议您尽可能多地从Apache那里负责并设置一个“调度程序”脚本,通过检查请求的URI来决定执行哪个PHP文件。

这个想法非常简单:将每个请求“重定向”到一个 PHP文件,然后使用该文件确定您实际要执行的文件。

E.g。

http://domain.com/ =&gt;的index.php?请求=

http://domain.com/moo/ =&gt;的index.php?请求=も/

http://domain.com/moo/1/2/3/4/ =&gt;的index.php?请求=も/ 1/2/3/4 /

等等

示例:

(假设您的网络根目录中有.htaccess和index.php文件)

<强> htaccess的:

# "Hi Apache, we're going to be rewriting requests now!"
# (You can do all this in Apache configuration files too, of course)
RewriteEngine On
RewriteBase /

# Ignore *.gif, *.jpg. *.png, *.js, and *.css requests, so those files
# will continue to be served as per usual
RewriteRule \.(gif|jpg|png|js|css)$ - [L]

# For the rest, convert the URI into $_GET[ 'request' ]
RewriteRule ^(.*)$ index.php?request=$1 [QSA] [L]

<强>的index.php:

<?php

print "<pre>Request: " . $_GET[ 'request' ] . "\n";

// Dispatcher should be smarter than this -- otherwise you
// will have serious security concerns

$filename = $_GET[ 'request' ] . '.php';

if( file_exists( $filename ) === TRUE )
    require( $filename );
else
    print "Not found: $filename";