Question

I am working on a LAMP setup on a shared HostGator server. I am currently trying to create more friendly urls.

I need to forward addresses like this:

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

to here:

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

without changing the address bar. My current rewrite rule looks like this:

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

Adding the P flag was the only way that I could get it to load without changing the address, but it seems to be breaking my javascript.

What do I need to do in order to make this work without breaking the js? AND What should the regex in the rewrite rule look like to get the id(should be everything after the last dash) into that variable?

Here is my entire .htaccess file in case something may be interfering:

#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
Était-ce utile?

La solution

You don't need the P flag, since this is all on the same server, you don't need to proxy. Your pattern is close but also matches the title and .htm part of the URI. Try something like:

RewriteRule ^posts/[^/]+/[^.]+-([0-9]+)\.html?$ /viewpost.php?id=$1 [L,NC]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top