Fraser
Fraser

Reputation: 14246

mod-rewrite to strip out sub directory in .htaccess

How would I rewrite a URL such as:

http://www.site.com/sub-directory/page-name

to

http://www.site.com/page-name

?

Upvotes: 0

Views: 208

Answers (2)

Alvin Wong
Alvin Wong

Reputation: 12410

I believe your intended solution is using Virtual Hosts, but if you don't have access to the httpd.conf, you can try the following rewrite rules:

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} =host1.example.com
RewriteCond %{REQUEST_URI} !^/host1-dir
RewriteRule ^(.*) host1-dir/$1 [L]

RewriteCond %{HTTP_HOST} =host2.example.com
RewriteCond %{REQUEST_URI} !^/host2-dir
RewriteRule ^(.*) host2-dir/$1 [L]

RewriteCond %{HTTP_HOST} =host3.example.com
RewriteCond %{REQUEST_URI} !^/host3-dir
RewriteRule ^(.*) host3-dir/$1 [L]

# If doesn't match any of it then 404 Not Found or anything you like
RewriteCond %{HTTP_HOST} =host1.example.com
RewriteCond %{HTTP_HOST} =host2.example.com
RewriteCond %{HTTP_HOST} =host3.example.com
RewriteRule .* - [R=404,L]

Upvotes: 1

Ondra Žižka
Ondra Žižka

Reputation: 46796

IIRC mod_rewrite supports regex, so you can use it's replace:

^(.*/)[^/]*& 

The parens match all up to last /.

Then you re-use it using group reference, I think it's $1. The rest is dropped.

Check mod_rewrite help on how to use regexp.

Upvotes: 0

Related Questions