首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重写/重定向有关扩展和斜杠的问题

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

Stack Overflow用户
提问于 2011-09-12 02:19:24
回答 1查看 147关注 0票数 1

我试图从我的PHP页面做一个很好的,SEO友好的URL,但是我经常遇到500个内部错误,所以我被困住了。下面是下面的内容:

文件夹结构

代码语言:javascript
复制
  /    
    /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和其他地方的例子。对我来说,阿帕奇就像伏都教,有时候它会做一些神奇的事情,但有时它就是不起作用。下面是我到目前为止掌握的代码:

代码语言:javascript
复制
#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]
EN

回答 1

Stack Overflow用户

发布于 2011-09-23 16:43:16

我会以不同的方式对待这件事。如果您对Apache不太熟悉,那么我的建议是尽可能地从Apache中承担更多的责任,并设置一个"dispatcher“脚本,通过检查请求的URI来决定执行哪个PHP文件。

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

例如。

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

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

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

等等

示例:

(这是假设您的web根目录中有.htaccess和index.php文件)

.htaccess:

代码语言:javascript
复制
# "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:

代码语言:javascript
复制
<?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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7382737

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档