Dejvid
Dejvid

Reputation: 470

Can't rewrite and redirect a url properly in .htaccess

I am trying to make the url(s) in my website user friendly, but it seems like .htaccess rewrite commands are not taken into consideration at all by the server.

The project is in the localhost and it is named ecommerce. I want to "convert" this url: localhost/ecommerce/product?name=abc to localhost/ecommerce/product/abc.

Here is the .htaccess file:

RewriteEngine On
RewriteBase /

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

##hide /index
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\index [NC]
RewriteRule ^ %1 [R,L,NC]


##HERE IS THE IMPORTANT PART
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD)\ /product\.php\?name=([^&]+)
RewriteRule ^ /product/%2/? [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?product/([^/]+)/?$ /product.php?name=$1 [L]

When I visit localhost/ecommerce/product?name=abc the url remains as it is and when I visit localhost/ecommerce/product/abc I get 500 Internal Server Error.

I thought there was a problem with xampp httpd.conf, so I changed

<Directory />
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

to

<Directory />
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

and it still doesn't work!

Removing the part where I hide the .php extension from .htaccess also doesn't make any difference.

Upvotes: 2

Views: 135

Answers (1)

anubhava
anubhava

Reputation: 784898

Replace your code with this inside /ecommerce/.htaccess:

Options -MultiViews
RewriteEngine On
RewriteBase /ecommerce/

##HERE IS THE IMPORTANT PART
RewriteCond %{THE_REQUEST} /product\.php\?name=([^&\s]+) [NC]
RewriteRule ^ product/%1/? [L,R=301]

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s/+(.*?/)?(?:index|(\S+?))\.php[/\s?] [NC]
RewriteRule ^ /%1%2 [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?product/([^/]+)/?$ product.php?name=$1 [L,NC,QSA]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Make sure to test it in a new browser to avoid old browser cache.

Upvotes: 2

Related Questions