【问题标题】:Rewrite/redirect question regarding extensions and slashes关于扩展名和斜杠的重写/重定向问题
【发布时间】:2011-09-24 00:43:16
【问题描述】:

我正在尝试从我的 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]

【问题讨论】:

  • 只是一个评论;尾部斜杠表示子内容,斜杠通常是前一个标记的子项。如果你真的是说你看到的资源是我们的人,那么它可能应该是 www.example.com/about/our-people,我敢打赌,这个尾部斜线重写是你的罪魁祸首。
  • 现在,当我输入 www.example.com/about/our-people/ 时,上面的代码给我一个内部服务器错误,但该页面适用于 www.example/about/our-people和 www.example/about/our-people.php ...但是我不希望它这样做,我希望它转到第一个 URL!
  • :) 是的,我知道这就是你想要的,我想说的是,这也许不是最明智的(也不是最有意义的)事情。
  • 我正在阅读与 SEO 相关的文章,他们都提到要删除扩展名并添加斜杠。大多数 CMS'es 我以这种方式使用重写 URL,所以我想效仿。从任何角度来看,拥有 1 个规范的 URL 版本(以避免重复)不是一个好主意。我不知道,就像我之前提到的,URL 重写对我来说很奇怪:/

标签: php apache .htaccess mod-rewrite redirect


【解决方案1】:

我会以不同的方式处理这个问题。如果您对 Apache 不是很熟悉,那么我的建议是您尽可能多地从 Apache 承担责任,并设置一个“调度程序”脚本,通过检查请求的 URI 来决定执行哪个 PHP 文件。

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

例如

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/

等等

例子:

(假设您的网络根目录中有 .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";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2011-09-13
    • 1970-01-01
    • 2015-10-11
    相关资源
    最近更新 更多