在不更改地址栏的情况下,使用.htaccess重写URL



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

我需要转发这样的地址:

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的情况下完成这项工作?以及重写规则中的regex应该是什么样子才能将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

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

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

最新更新