Thin htaccess problem. I'm going crazy

I want my main domain to be located from a subdirectory (finalized this step somewhat), i.e. when someone types on www.example.com/news backstage, he will go to www.example.com/subdirectory/ but it will still appear as www.example.com/news.

I used the following code to run:

RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?example.com$ RewriteCond %{REQUEST_URI} !^/subdirectory/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /subdirectory/$1 RewriteCond %{HTTP_HOST} ^(www.)?example.com$ RewriteRule ^(/)?$ subdirectory/index.php [L] 

This code works if I type on www.example.com/news/ (pay attention to the trailing slash), but DOES NOT work if I just type www.example.com/news (without a slash). Any ideas why?

Thanks.

+4
source share
3 answers

I think the problem is that after Apache overwrites / news into the / subdirectory / news, it finds itself with a request corresponding to a directory in the file system that does NOT end with a trailing slash. Therefore, it issues a redirect to the new URL, including the trailing slash.

The thing is, in fact, we want the handle to be added to preserve the canonical URL (otherwise we end up with / news and / news / leading to the same place - not good for relative links, SEO, etc.), just not quite the way Apache does it. Therefore, we must do it ourselves by adding the following:

 RewriteCond %{REQUEST_URI} ^/subdirectory/.*[^/]$ RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^subdirectory/(.*)$ /$1/ [L,R=301] 

The conditions of this rule will correspond to any requests starting with a "subdirectory", DO matches the directory on fielsysem, but does not end with a slash. (e.g. '/ subdirectory / news'). The rewriting program then provides a constant redirect to the same path, but ends with a slash and disables "subdiretcory" (for example, "/ news / ').

The client then issues a request to '/ news /', apache rewrites this to / subdirectory / news / and will not issue a redirect because it ends with a slash.

Quickly checked it out and seemed to do the trick.

+1
source

Not quite the answer to your question, but is it easier

  • Change your DocumentRoot to a public directory or if you cannot do this (e.g. on a shared host) ...
  • Put the public files in your root directory (public_html or something else) and application files somewhere outside it (or if you cannot go over the document root inside it, but are protected from network access using Deny from all
0
source

andrewmabbott is correct and you need to use ProxyPassReverse to fix it . This will rewrite all redirects to use the correct address.

The easiest way to do this:

 ProxyPassReverse /subdirectory http://www.example.com/ 

However, bluehost could disable mod_proxy, in which case this will not work.

0
source

All Articles