0

I've got an apache website stored on the server at /var/www/website/ and it's the only one on that server. I'd like to adjust the URL accordingly. How can I make an .htaccess rule that would do this?

before: https://example.com/website/index.php
after: https://example.com/

  • 1
    Why wouldn't you just put the index.php file into /var/www/ directly? If you do that, what you want automatically happens. Alternately, you could edit your webserver config to set the DocumentRoot to /var/www/website/ rather than /var/www/. Both of those are simple changes that prevent a lot of ugliness in .htaccess – Stephen Ostermiller May 13 at 10:28
  • That's a workable method, and the end I did go with the DocumentRoot setting you suggested, but nevertheless I had the question about how to do it with .htaccess and would still like to learn that method, even if only for curiosity's sake. – Dylan Kinnett May 14 at 15:32
1

There's not a lot of information here. For instance, what do you want to happen with all your other URLs (do you have any other URLs)? For the sake of this answer I assume you just have a single URL, / that needs to rewrite to /website/index.php (as stated in your question).

Anyway, you don't do this entirely in .htaccess. The first thing you must do is:

  1. Change the URL in your application. Change your links to point to https://example.com/ (not https://example.com/website/index.php)

  2. You can then use mod_rewrite in .htaccess to internally rewrite the URL from https://example.com/ to https://example.com/website/index.php (the underlying filesystem path):

    RewriteEngine On
    
    # Rewrite "/" to "/website/index.php"
    RewriteRule ^$ /website/index.php [L]
    
  3. Optionally, if you are changing an existing URL structure and you need to preserve SEO then you can also implement an external redirect from /website/index.php to /. However, you must only do this if you have implemented step #1 above. This goes before the above rewrite:

    # Redirect "/website/index.php" to "/"
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteRule ^website/index\.php$ / [R=302,L]
    

    The RewriteCond (condition) is necessarily to prevent a redirect loop. To prevent the rewritten URL (above) being redirected.

    (Change to a 301 only after you have tested that this works OK - to avoid caching issues whilst testing.)

In Summary:

RewriteEngine On

# Redirect "/website/index.php" to "/"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^website/index\.php$ / [R=302,L]

# Rewrite "/" to "/website/index.php"
RewriteRule ^$ /website/index.php [L]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.