Search code examples
apache.htaccessmod-rewriteseodirectoryindex

.htaccess prevent subdirectory browsing and update URL in browser


I'm trying to prevent browsing of files in a subdirectory by displaying a specific page, at the same time as preventing duplicate content on two URLs.

I have several files in a subdirectory, for example:

www.example.com/subfolderA/pageone.html

www.example.com/subfolderA/pagetwo.html

www.example.com/subfolderA/pagethree.html etc

I do not want users to access the subdirectory itself (www.example.com/subfolderA/) and see a list of all the files. Instead I would like them to be directed to a specific page (that isn't necessarily called "index.html"), let's say pageone.html.

I have put the following in a .htaccess file within that subdirectory:

DirectoryIndex pageone.html

Whilst this prevents browsing of files and shows my desired page, it results in duplicate pages appearing in search engines.

www.example.com/subfolderA/ and www.example.com/subfolderA/pageone.html

How can I also ensure that the subdirectory itself doesn't get indexed by the search engines - i.e. always update the URL in the browser to www.example.com/subfolderA/pageone.html?

Also is this the best solution to meet my requirement?

Any help appreciated.

Thanks.


Solution

  • To remove duplicate pages you can have this rule in /subfolderA/.htaccess:

    RewriteEngine On
    RewriteBase /subfolderA/
    
    RewriteCond %{THE_REQUEST} (/subfolderA)/?[?\s] [NC]
    RewriteRule ^$ %1/pageone.html [L,R=301]