使用RewriteCond更改我的链接

时间:2013-07-04 05:25:29

标签: .htaccess url mod-rewrite url-rewriting

我是新手。我正在尝试清理我的链接。我试着在这里看一些答案。我相信我甚至不能接近......!你可以帮助我吗?

目前我的链接结构就是这个......

xyz.com/viewgallery.php?cname=Colorado-Fall&pcaption=Touched-By-Light

但我希望观看者看到此链接xyz.com/viewgallery/Colorado-Fall/Touched-By-Light(这意味着重定向?)

然后重写回我的链接。 (这是我理解的方式)......

所以我写了......

检查实际请求是否为“this1”

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /viewgallery.php\?cname=(.*)&pcaption=(.+)

# redirect to "this2"
RewriteRule ^viewgallery\.php /%1/%2/?%3 [R=301,L]

# now rewrite "this2" back to "this1"
RewriteRule ^(.*?)/(.+)$ /viewgallery.php?cname=$1&pcaption=$2 [L,QSA]

这是对的吗?我确信它看起来像是胡言乱语......对此有所了解!...

感谢您的帮助..

1 个答案:

答案 0 :(得分:1)

通过httpd.conf启用mod_rewrite和.htaccess,然后将此代码放在.htaccess目录下的DOCUMENT_ROOT中:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# externally redirect /viewgallery.php?cname=Colorado-Fall&pcaption=Touched-By-Light to 
# /viewgallery/Colorado-Fall/Touched-By-Light to 
# RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(viewgallery)\.php\?cname=([^&]+)&pcaption=([^&\s]+) [NC]
# RewriteRule ^ /%1/%2/%3? [L,R=301,NE]

# internally forward /viewgallery/Colorado-Fall/Touched-By-Light to 
# /viewgallery.php?cname=Colorado-Fall&pcaption=Touched-By-Light
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ /$1.php?cname=$2&pcaption=$3 [L,QSA]

<强>解释

  1. 规则1用于外部重定向以使您的网址漂亮
  2. 它在%1,%2,%3中捕获“viewgallery”和参数cname和pcaption的值
  3. 此后,这些捕获的变量用于创建漂亮的网址/viewgallery/%2/%3
  4. 规则2适用于内部转发
  5. 从网址:/viewgallery/Colorado-Fall/Touched-By-Light它捕获3个变量:“viewgallery”,“Colorado-Fall”和“Touched-By-Light”分为1美元,2美元,3美元
  6. 捕获的变量用于构建真实的网址:/viewgallery.php?cname=$2&pcaption=$3
  7. <强>更新

    # /viewgallery.php?cname=Colorado-Fall&pcaption=Poked to /photos/Colorado-Fall/Poked.jpg
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+viewgallery\.php\?cname=([^&])+&pcaption=([^&\s]+) [NC]
    RewriteRule ^ /photos/%1/%2.jpg? [R=301,L]
    
    RewriteRule ^photos/([^/]+)/([^.]+)\.jpg$ /viewgallery.php?cname=$1&pcaption=$2 [QSA,L,NC]