odd_duck
odd_duck

Reputation: 4101

htaccess - remove directory names from URL

I Have the following site structure:

- index.php
- css/
- js/
- img/
- content/
  - product/
    - product-page-1.php
    - product-page-2.php 
  - static/
    - faqs.php
  - landing/
    - homeware-gifts.php 
    - stationary/
      - desks.php 

So at the moment some of my URL's are like so but I need to hide the content and product, static, landing directories

Products:

mysite.com/content/product/product-page-2.php

to

mysite.com/product-page-2

Static:

mysite.com/content/static/faqs.php

to

mysite.com/faqs

Landing:

mysite.com/content/landing/homeware-gifts.php
mysite.com/content/landing/stationary/desks.php

to

mysite.com/homeware-gifts
mysite.com/stationary/desks

Note I am also wanting to hide the .php extension and I am currently using this:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

Which works but need to make sure that stays as well

Upvotes: 2

Views: 1509

Answers (2)

anubhava
anubhava

Reputation: 784898

You may use these rules in your site root .htaccess:

RewriteEngine On

## hide .php extension
# To externally redirect /content/file.php to /file
RewriteCond %{THE_REQUEST} \s/+site1/content/(.+?)\.php[\s?] [NC]
RewriteRule ^ /site1/%1 [R=301,NE,L]

## To internally rewrite /file to /content/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/site1/content/$1.php -f
RewriteRule ^site1/(.+?)/?$ site1/content/$1.php [L,NC]

This assumes there is no .htaccess inside site1/ or anywhere else.

Upvotes: 1

jusdepatate
jusdepatate

Reputation: 30

Assuming that your web server is Apache2, you have to put this in your vhost config :

    <Directory "/path/to/webroot">
         Options Indexes FollowSymLinks MultiViews
         AllowOverride all
         Order allow,deny
         allow from all
    </Directory>

And then you will be able to play with .htaccess, first you will have to add

    Options +FollowSymlinks
    RewriteEngine On

in all .htaccess and use this template :

    RewriteRule ^MySuperRewritePath$  /my/path/without/rewrite.php [L]

(As far as I know, you don't need to put a .php in rewrited URLs, so that's good for what you want)

Check out official docs if you want more infos

Upvotes: 0

Related Questions