narasi
narasi

Reputation: 463

URL rewrite to remove trailing folder name

We have a server, and have several folders under the /var/www/ folder. We have pointed our domain name to the IP of the server, and by default we expect to load one folder as the website (since its not possible to point a folder with DNS).

I have written .htaccess in such a way that when you enter the IP or the domain name, the request redirects to the website folder.

However, whenever we enter the IP or the domain name, the name of the folder is getting added to the URL.

Here is the present .htaccess:

Options +FollowSymlinks -Multiviews
    #DirectoryIndex folder/
    RewriteEngine on
    ReWriteBase /
    RewriteRule ^$ /folder [L]
    RewriteRule ^$ folder/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+folder/([^\s]+) [NC]
    RewriteRule ^ %1 [R=301,L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule (?!^folder/)^(.*)$ /folder/$1 [L,NC]

where the folder is the folder's website so,

www.domain.com

becomes

www.domain.com/folder/

Is there a way to rewrite the URL to remove the folder name?

Thanks in advance :)

EDIT : Added .htaccess code

Upvotes: 0

Views: 824

Answers (2)

anubhava
anubhava

Reputation: 785611

Have your rule like this in DocumentRoot/.htacess:

DirectorySlash On
Options +FollowSymlinks -MultiViews
RewriteEngine on
ReWriteBase /

# redirect /folder/abc123 to /abc123
RewriteCond %{THE_REQUEST} \s/+folder/(\S*) [NC]
RewriteRule ^ /%1 [R=301,L,NE]

# skip rewrites for real files/directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule !^(index\.)?$ - [L]

# route everything internally to /folder
RewriteRule ^((?!folder/).*)$ folder/$1 [L,NC]

Upvotes: 1

Sumurai8
Sumurai8

Reputation: 20737

It sounds like you made an external redirect instead of an internal rewrite. An external redirect is denoted by the [R] flag (with optional parameter) and causes Apache to send a 301 or 302 header back to the client with a different url that client should request. This causes the client to show the new url in the address bar.

What you want is an internal rewrite. When you request the url, the url is internally rewritten to the place where the resource is actually located. You do this by omitting the [R] flag, and not using a domain name in the rewritten part. It typically looks something like this:

RewriteCond %{REQUEST_URI} !^/folder
RewriteRule ^(.*)$ /folder/$1 [L]

Upvotes: 1

Related Questions