开发者

Rewrite/redirect question regarding extensions and slashes

I'm trying to make nice, SEO Friendly URLs from my PHP pages, but I keep running into 500 Internal Errors and so I'm stuck. Here's the rundown:

Folder Structure

  /    
    /index.php
       /about      <--Folder
       /about/index.php   
       /about/our-people.php   <--a subpage
       /services   <--Another folder
       开发者_开发知识库/services/index.php
       /services/service1.php  <--another subpage

I want it to be so that the URLs don't have the .php extension but contain a trailing slash in place. So for instance the "Our People" page would be www.example.com/about/our-people/

www.example.com/about/our-people.php or www.example.com/about/our-people (no trailing slash) would go to www.example.com/about/our-people/

I know this question has probably been asked to death, but I've tried a lot of the examples out there from both Stackoverflow and other places. Apache is like voodoo to me, sometimes it does magical things, and sometimes it just doesn't work. Here's the code I have so far:

#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]


I would approach this a little differently. If you are not very familiar with Apache, then my recommendation would be that you take as much responsibility away from Apache as you can and set up a "dispatcher" script that decides which PHP file is executed by inspecting the requested URI.

The idea is pretty simple: "redirect" every request to one PHP file, and then use that file to determine which file you actually want to execute.

E.g.

http://domain.com/ => index.php?request=

http://domain.com/moo/ => index.php?request=moo/

http://domain.com/moo/1/2/3/4/ => index.php?request=moo/1/2/3/4/

Et cetera

Example:

(This is assuming you have .htaccess and index.php files in your web root)

.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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜