.HTACCESS技巧 - 重写动态内容

时间:2011-02-24 23:09:44

标签: apache mod-rewrite

我需要能够做到这一点,以便当有人访问我的网站时说:

a)http://www.mysite.com/article/this-article/

它实际上显示的内容来自:

b)http://www.mysite.com/article/index.php?src=this-article

并且如果用户键入(b),那么他们对(a)

301

在我的HT访问中,我目前有以下内容:

<IfModule mod_rewrite.c>
RewriteEngine on


# index.php to /
RewriteCond %{THE_REQUEST} ^GET\ /.*/index\.(php|html)\ HTTP
RewriteRule (.*)index\.(php|html)$ /$1 [R=301,L]

# force www.
rewritecond %{HTTP_HOST} ^mysite.com [nc]
rewriterule ^(.*)$ http://www.mysite.com/$1 [r=301,nc]

RewriteCond %{THE_REQUEST} ^GET\ /.*\;.*\ HTTP/
RewriteCond %{QUERY_STRING} !^$
RewriteRule .* http://www.mysite.com%{REQUEST_URI}? [R=301,L]

</IfModule>

1 个答案:

答案 0 :(得分:0)

我不确定你所描述的只能使用重写规则。但您可以使用重写规则和PHP的组合,如下所示:

将.htaccess文件更改为如下所示(注意:假设您的.htaccess文件位于根目录中)

<IfModule mod_rewrite.c>

  RewriteEngine On

  # force www.
  RewriteCond %{HTTP_HOST} !^www\.mysite\.com$ [NC]
  RewriteRule ^(.*)$ http://www.mysite.com/$1 [R=301,NC]

  RewriteCond %{REQUEST_URI} !^/article/index(-new)?\.php
  # this is looking for anything past article that is not a /. You may 
  # need to change that to be more inclusive - something like (.*)
  RewriteRule ^article/([^\/]+) /article/index-new.php?src=$1 [L,NC]

  # index.php to /
  RewriteRule ^index\.(php|html)$ / [R=301,L]
  #RewriteCond %{THE_REQUEST} ^GET\ /.*/index\.(php|html)\ HTTP
  #RewriteRule (.*)index\.(php|html)$ /$1 [R=301,L]

  RewriteCond %{THE_REQUEST} ^GET\ /.*\;.*\ HTTP/
  RewriteCond %{QUERY_STRING} !^$
  RewriteRule .* http://www.mysite.com%{REQUEST_URI}? [R=301,L]

</IfModule>

你的文章/ index.php将成为你的新index.php的重定向器,看起来像这样:

<?php
    if (isset($_GET["src"]))
        header("location: /article/" . basename($_GET["src"])); // Using basename() in case src happens to be referring to an actual file in your code
    else
        header("location: /");
?>

你的“真实”索引实际上是index-new.php,这是重写规则要调用的内容。