Server by default redirects users who type example.com/folder to example.com/folder/
Is there any way to change that (for example when they go to example.com/folder to redirect to otherexample.com/folder/). But this has to affect all folders but exclude the root. Also the code should do nothing when they type example.com/folder/.
Edit
Also the code should not affect images and all other files (or better say, if the requested document has file extension), just folders.
example:
should affect : example.com/folder
: example.com/folder/folder
but should not : example.com
: example.com/forum (but only forum, only this folder)
: example.com/folder/
: example.com/folder/.
: example.com/folder/folder/
: example.com/image.png
: example.com/something.something
: example.com/something.
: example.com/.something
Edit
And an other edit: Let's say we found the .htaccess code (the 1st answer below). How do I make it work for all my domain and website expect my blog (example.com/blog) which I don't want to have redirections like whole my website?
Server by default redirects users who type example.com/folder to example.com/folder/
That's done by mod_dir for several good reasons, all of which are explained in the DirectorySlash documentation. You could use DirectorySlash Off
to turn that behaviour off, but it is generally NOT a good idea to do that, unless you have VERY good and valid reasons to do so.
However, having said that, what you've described in your question can be handled by mod_rewrite alone. First, you need to check if the requested resource is a directory. It needs to be a physical directory inside your DocumentRoot
.
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
It is vitally important to also apply %{DOCUMENT_ROOT}
, otherwise the directory check won't work.
'-d' (is directory)
Treats the TestString as a pathname and tests whether or not it exists, and is a directory.
Second, you need to ignore all requests to directories that actually do have a trailing slash.
RewriteCond %{REQUEST_URI} !/$
Now you've filtered down to just the resources you want to redirect to another domain: directories without a trailing slash. Everything else (directories with trailing slashes, images, etc.) is not even in the game at this point. Time for the actual redirect.
RewriteRule ^ http://other.com%{REQUEST_URI}/ [redirect=temp,last]
You might want to change your mind later on about the redirection, so you should use temporary redirects (a.k.a. 302 Found) instead of permanent ones (a.k.a. 301 Moved Permanently). The last
tells mod_rewrite to stop all further processing.
And here's the final product:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^ http://other.com%{REQUEST_URI}/ [redirect=temp,last]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With