Search code examples
.htaccess

Edit or create .htaccess file to redirect folder to a page


I have an .htaccess file in the folder public_html, so that my directory looks like this:

public_html
    = cgi-bin/
    = images/
    = other/
    - index.html
    - .htaccess

The .htaccess file reroutes www.example.com to example.com. I copied the following code from the web and it works thus far:

# Remove www from any URLs that have them:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

Now, If anyone visits www.example.com/other or example.com/other or example.com/other/ there is a Forbidden page error. I would like to reroute any of those requests to:

  • example.com/other/sub/index.html

How can I extend the existing .htaccess file (or create a new one in a subfolder) to achieve this? (note no need to mask any addresses in the browser bar)

Appreciate any solution and brief explanation...


Solution

  • You add a specific redirection rule for that specific path /other:

    RewriteEngine on
    # remove www from any request host name
    RewriteCond %{HTTP_HOST} ^www\.
    RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
    # redirect any requests to /other
    RewriteRule ^/?other/?$ /other/sub/index.html [R=301,L]
    

    The rule will get applied to all requests to a path /other or /other/ and redirect those. That is what I understood from the question. It will not interfere with any requests to anything under that path, so for example /other/foo, you did not mention any such thing.

    I also took the liberty to simplify your existing rule to remove the "www." prefix from the host name.

    Both rules can be implemented in a single distributed configuration file inside the DocumentRoot folder of your site. In general you should prefer to implement rules in the central virtual host configuration, that is less complex and more efficient, but you need access to the central configuration of the http server for that. So you need to be in control of that server. You won't be able to do that if you are using a simple web space provider. The way above rules are implemented here can be used in both setups, though, without any modification.