使用.htaccess重写URL而不更改地址栏

时间:2013-08-07 17:42:39

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

我正在共享HostGator服务器上进行LAMP设置。我目前正在尝试创建更友好的网址。

我需要转发这样的地址:

  

http://usafarmtrader.com/posts/city-state/title-3869.htm

到这里:

  

http://usafarmtrader.com/viewpost.php?id=3869

不更改地址栏。我目前的重写规则如下:

RewriteRule ^posts/(.*)/(.*)? http://usafarmtrader.com/viewpost.php?id=$2 [L,NC,P]

添加P标志是我可以在不更改地址的情况下加载它的唯一方法,但它似乎打破了我的javascript。

为了在不破坏js的情况下完成这项工作,我需要做些什么?和 重写规则中的正则表达式应该如何将id(应该是最后一个破折号后的所有内容)转换为该变量?

这是我的整个.htaccess文件,以防有些事情可能会干扰:

#RewriteCond %{REQUEST_URI} !^/js/.*$
#RewriteCond %{REQUEST_URI} !^/img/.*$
#RewriteCond %{REQUEST_URI} !^/css/.*$
#RewriteCond %{REQUEST_URI} !^/inc/.*$
#RewriteCond %{HTTP_HOST} ^usafarmtrader.com$
#RewriteRule !^down\.php$ http://usafarmtrader.com/down.php [R=302,L]

ErrorDocument 404 /index.php

RewriteEngine On

RewriteRule ^(js|img|fonts)/ - [L]

#RewriteRule ^posts/(.*)/(.*)? http://usafarmtrader.com/viewpost.php?id=$2 [L,NC,P]
RewriteRule ^posts/[^/]+/[^.]+-([0-9]+)\.html?$ http://usafarmtrader.com/viewpost.php?id=$1 [L,NC]

RewriteCond %{SERVER_PORT} 80
RewriteRule ^mylistings\.php|login\.php|myaccount\.php|newaccount\.php|reset\.php|newpost\.php|editpost\.php$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{SERVER_PORT} 443
RewriteRule ^about\.php|contact\.php|down\.php|faq\.php|find\.php|forgot\.php|home\.php|index\.php|viewpost\.php$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Google Analytics Integration - Added by cPanel.
<IfModule mod_substitute.c>
AddOutputFilterByType SUBSTITUTE text/html
Substitute "s|(<script src='/google_analytics_auto.js'></script>)?</head>|<script src='/google_analytics_auto.js'></script></head>|i"
</IfModule>
# END Google Analytics Integration

# Use PHP 5.3
AddHandler application/x-httpd-php53 .php

1 个答案:

答案 0 :(得分:1)

您不需要P标志,因为这一切都在同一台服务器上,您不需要代理。您的模式很接近,但也匹配URI的标题 .htm 部分。尝试类似:

RewriteRule ^posts/[^/]+/[^.]+-([0-9]+)\.html?$ /viewpost.php?id=$1 [L,NC]