Rewrite Rule with dynamic hostname - apache

I'm interesting in rewrite rule to modify some url and paths. Here some Examples.
I have some hostnames which lookups to 1 VirtualHost throught ServerAlias in Apache conf.
example.com
anotherdomain.com
same.org
And a lot of anothers domains. Here, what I want to do:
example.com/uploads/photo.png -> /www/example.com/uploads/example.com/photo.png<br />
anotherdomain.com/uploads/photo.png -> /www/anotherdomain.com/uploads/anotherdomain.com/photo.png<br />
And same thing with another domains. This thing I've made already.
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^uploads/([a-zA-Z0-9-\._]+)$ uploads/%2/$1 [L]
This work perfectly. But, if I try to access uploads/icons/category/image.png
I start to see 500 Internal Apache Error...
I've modify Rule to this:
RewriteCond %{REQUEST_URI} !^/uploads/%{HTTP_HOST}
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^uploads/([a-zA-Z0-9-\._/]+)$ uploads/%2/$1 [L]
And Enable Apache Rewrite log with 9 verbosity.
RewriteCond: input='/uploads/icons/category/image.png' pattern='!^/uploads/%{HTTP_HOST}' => matched
rewrite 'uploads/icons/category/image.png' -> 'uploads/example.com/icons/category/image.png'
RewriteCond: input='/uploads/example.com/icons/category/image.png' pattern='!^/uploads/%{HTTP_HOST}' => matched
rewrite 'uploads/example.com/icons/category/image.png' -> 'uploads/example.com/example.com/icons/category/image.png'
And after that, it's exhausts 10 lookups =(
When I modify to this
RewriteCond %{REQUEST_URI} !^/uploads/example.com
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^uploads/([a-zA-Z0-9-\._/]+)$ uploads/%2/$1 [L]
It's works perfectle for ALL stuff, but only for 1 domain: example.com
I found another solution, but it's not a perfect.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteRule ^uploads/([a-zA-Z0-9-\._/]+)$ uploads/%2/$1 [L]
This Rule works only if I have existed dir and file. But, if i try to access:
/uploads/images/not-existed-404.nothing -> It return 500, because this file doesn't exists and rewriting into:
/uploads/example.com/example.com/example.com/example.com.......
P.S. Sorry for my bad English ;)

RewriteCond %{REQUEST_URI} !^/uploads/%{HTTP_HOST}
You CANNOT use variables or back references in pattern -- i.e. %{HTTP_HOST} will not be expanded to example.com, instead it will be treated as normal text.
You can uses these rules (working fine on my PC):
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteCond %{DOCUMENT_ROOT}/uploads/%2/$1 -f
RewriteRule ^uploads/(.+)$ uploads/%2/$1 [L]
This rule will check if target file does exist and only then rewrites (order of conditions matter).
Let's assume:
domain name: example.com
website root: /www/example.com/
URL requested: /uploads/img/meow.png
Second condition (RewriteCond %{DOCUMENT_ROOT}/uploads/%2/$1 -f) will check if file /www/example.com/uploads/example.com/img/meow.png exists, and if it does -- then rewrite occurs.
Your .htaccess then may look like this:
RewriteEngine On
RewriteBase /
# do not do anything for already existing files & folders
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .+ - [L]
# rewrite uploads to domain-specific folder
RewriteCond %{HTTP_HOST} ^(www\.)?(.*)$
RewriteCond %{DOCUMENT_ROOT}/uploads/%2/$1 -f
RewriteRule ^uploads/(.+)$ uploads/%2/$1 [L]

Related

.htaccess redirect based on folder

I need help with .htaccess Rewrite rules.
I have a API which can be accessed over http://api.my.domain/products/all which is working fine and is returning result.
I would like to redirect users coming to http://api.my.domain/admin to admin folder.But it is not working with current rules.
I have added this to .htaccess but it is not working correctly for admin folder.
RewriteEngine On
RewriteCond %{Request_Filename} !-F
RewriteCond %{Request_Filename} !-d
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^admin admin/index.php [QSD,L]
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^ public/index.php [QSD,L]
This is the result I get when I enter http://api.my.domain/admin and is breaking all my php redirects:
http://api.drezga.hr/admin/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/admin/admin/checklogin.php
Can someone, please, tell me what I'm doing wrong? I have spent hours and I can't see it.
Aside: If /admin is a physical directory then you should be requesting /admin/ (with a trailing slash) to begin with, otherwise Apache/mod_dir will issue a 301 redirect to append the trailing slash.
RewriteCond %{Request_Filename} !-F
RewriteCond %{Request_Filename} !-d
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^admin admin/index.php [QSD,L]
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^ public/index.php [QSD,L]
The first two conditions (RewriteCond directives) are being applied incorrectly to the first rule only. They need to apply to the last rule (the rewrite to public/index.php) then the rewrite to admin/index.php is not necessary (this should be handled by the DirectoryIndex).
There's no need for the QSD flag since you are checking that the query string is already empty - there is no query string to discard!
You should probably be using the -f operator on the condition, not -F (which uses subrequests and is consequently less efficient).
Try the following instead:
DirectoryIndex index.php
RewriteEngine On
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Optimisation (prevent additional filesystem check)
RewriteRule ^public/index\.php$ - [L]
RewriteCond %{QUERY_STRING} ^$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . public/index.php [L]
RewriteRule ^$ public/index.php [L]
The RewriteCond %{REQUEST_FILENAME} !-d directive prevents requests for /admin/ being passed to public/index.php.
The additional RewriteRule at the end is to rewrite requests for the root directory, which would otherwise be omitted because of the condition mentioned above. This could be avoided by extending the DirectoryIndex directive instead, although this could change the behaviour if you have other directories that need to be accessible (or should not be routed to public/index.php). For example:
DirectoryIndex index.php /public/index.php

.htaccess language based RewriteRule like example.com/en/

I'm trying to write redirect directives in the .htaccess to forward internally all user requests like this:
Every request in a language folder should redirect to the requested file with the language query string:
example.com/en/contact.php -> example.com/contact.php?lang=en
Redirect any request without language path to a default language folder like this:
example.com -> example.com/en
Remove trailing slash if the address is entered with it:
example.com/en/ to example.com/en
For the folder projects, every request should lead to the view-project.php file with the respective query strings:
example.com/en/projects/test -> example.com/view-project.php?lang=en&path=test
Here is my attempt, but it's not working without trailing slash on a request like: http://www.example.com/de and is not redirecting http://www.example.com to a default language folder.
RewriteEngine On
RewriteRule ^(en|de)/(.*)$ $2?lang=$1 [L,QSA,NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^projects/([^/\.]+)/?$ view-project.php?path=$1 [QSA,L]
How can I achieve this?
This is possible a duplicate and I apologize for that. I searched everywhere and read about 100 posts, but I did't found what I'm looking for.
after struggling a while and with the help of someone else, here is the .htaccess file that works for me:
RewriteBase /example.com/
DirectorySlash Off
RewriteEngine On
RewriteOptions AllowNoSlash
RewriteRule ^$ de [R=301,L]
RewriteRule ^(de|en)/$ $1 [R=301,L]
RewriteRule ^(de|en)$ index.php?lang=$1 [L]
RewriteRule ^(de|en)/projects/(.+) view-project.php?lang=$1&path=$2 [L,QSA]
RewriteRule ^(de|en)/(.+) $2?lang=$1 [L,QSA]
Try:
RewriteEngine On
RewriteBase /mysite.com/
RewriteCond %{HTTP:Accept-Language} (en|de) [NC]
RewriteRule ^ /%1/index.php [L]
RewriteCond %{HTTP:Accept-Language} (en|de)
RewriteCond %{DOCUMENT_ROOT}%1%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^(en|de)/(.+)$ $2&lang=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^projects/([^/\.]+)/?$ view-project.php?path=$1 [QSA,L]
Edit:
The above was before the detailed explanation: After the detailed explanation, I've come up with this solution which is very similar to the solution the author has come up with while I was not aware about the edit explaining the situation:
DirectorySlash Off # disables mod_dir slash redirect
RewriteEngine On
RewriteBase /mysite.com/ # rewrites inside /mysite.com/
RewriteOptions AllowNoSlash # stops ignoring the directory redirects that redirect directories without slash, so by default: example.com/dir1 -> example.com/dir2 would be ignored. This is used because DirectorySlash is off
RewriteRule ^(en|de)\/projects\/(.+)$ view-project.php?lang=$1&path=$2 [QSA,L] # rule 4
RewriteRule ^(en|de)\/(.*)$ $2?lang=$1 [QSA,L] # rule 1
RewriteRule ^$ en [R=302,L] # rule 2
RewriteRule ^(en|de)\/$ $1 [R=302,L] # rule 3

htaccess redirect all subdomains to the same directory

I want to be able to redirect all subdomains to a folder:
RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$
RewriteRule (.+)$ "http://example.com/subdomains/%1" [L,P]
for example, if some visits sub1.example.com it will keep the URL but show example.com/subdomains/sub1 and if the sub1 directory does not exist, it will show example.com/404
Is this possible?
I tried the above code but its showing me:
Forbidden
You don't have permission to access /index.php on this server.
Wordpress says:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
and at the top of my htaccess file, is:
RewriteEngine On
DirectoryIndex index.php
RewriteCond %{HTTP_HOST} admin.domain.com$
RewriteRule ^(.*)$ /admin/system/$1 [L]
Your above .htaccess would externally redirect the calls, as you use a full URL as the target.
In your question you say you want to keep the hostname, so I will assume that is the requirement.
0) Enable rewrite engine
RewriteEngine On
1) Rewriting known subdomains to their directory in /subdomains
# Rewrite known subdomains to /subdomains/{subdomain}/
RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$
RewriteCond %{REQUEST_URI} !^/subdomains [NC]
RewriteCond %{REQUEST_URI} !^/404 [NC]
RewriteRule ^(.+)$ /subdomains/%1/ [L]
When we encounter a request with a subdomain,
and we have not rewritten it to /subdomains
and we have not rewritten it to /404
then rewrite it to /subdomains/{subdomain}/
So, if the request was
http://foo.example.com/hello
the URL in the browser would stay the same, but internally be mapped to
/subdomains/foo/
2) Rewriting unknown subdomains to /404
# Rewrite missing unknown subdomains to /404/
RewriteCond %{HTTP_HOST} ^([^/.]+)\.example\.com$
RewriteCond %{REQUEST_URI} ^/subdomains [NC]
RewriteCond %{REQUEST_URI} !^/404 [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ /404/ [L]
When we encounter a request with a subdomain,
and we have already rewritten it to /subdomains
and we have not rewritten it to /404
and it is not existing as a file
and it is not existing as a directory
and it is not existing as a symlink
then rewrite it to /404
So, if the request was
http://bar.example.com/hello
the URL in the browser would stay the same, but internally be mapped to
/subdomains/bar/
by the first RewriteRule from 1).
If /subdomains/bar/ does not exist, the second RewriteRule from 2) will kick in and internally map it to
/404/
3) Test-Environment
I actually tested all of this with exemplary code, available here: https://github.com/janpapenbrock/stackoverflow-36497197
I'd say you are experiencing a permission issue. I guess your Apache server runs as apache user. Use chmod to give apache access to this path.

mod_rewrite: how to redirect everything except 2 files to "/"?

I have a bit of a problem with a mod_rewrite configuration.
I want to redirect everything to the root directory (http://www.mydomain.com/), except for two files.
So I tried this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !^/
RewriteCond %{REQUEST_FILENAME} !/file1.html
RewriteCond %{REQUEST_FILENAME} !/file2.html
RewriteRule ^(.*)$ http://www.mydomain.com/ [L,R=301]
This unfortunetely doesn't redirect anything.
If I leave out the first RewriteCond line, I get a redirection error.
Where did I go wrong here?
First, you'll probably want to use REQUEST_URI instead of REQUEST_FILENAME. They may be the same in a virtual host scenario, but not normally. You're probably meaning to rewrite the URI, not the local path.
Secondly, your rule;
RewriteCond %{REQUEST_FILENAME} !^/
...excludes all requests to something starting with /, that is all URIs, from being rewritten. What you'll want to do is probably;
RewriteCond %{REQUEST_URI} !^/$
The rules for the ignored files should probably have an additional $ at the end to be an "ends with" match instead of a "contains" match.
That leaves something like;
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_URI} !/file1.html$
RewriteCond %{REQUEST_URI} !/file2.html$
RewriteRule ^(.*)$ http://www.mydomain.com/ [L,R=301]

Htaccess maintenance mode allow certain directories

So I use the following for to force my site into maintenance mode while updating certain things:
# MAINTENANCE-PAGE REDIRECT
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^23\.1\.12\.167
RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC]
RewriteRule .* /maintenance.html [R=302,L]
</IfModule>
This has worked well, but now I have the situation when in maintenance mode that I wish to exclude certain dir's from being sent to the maintenance.html and rather have them display their normal contents.
So it would be something like:
root/
.htaccess
maintenance.html
index.html
everything.else.html
/do_not_display_me
/display_me_always
Not sure if this is possible from the root level .htaccess or if I'm going to have to get crafty with sub-dir .htaccess files, any help is appreciated.
This should do the job. It tells Apache to not to rewrite those folders (which makes maintenance rules to be omitted as rewrite chain will never reach them).
# activate rewrite engine
RewriteEngine on
# always allow these folders
RewriteCond %{REQUEST_URI} ^/display_me_always [OR]
RewriteCond %{REQUEST_URI} ^/another_folder [OR]
RewriteCond %{REQUEST_URI} ^/even_more_folders
RewriteRule .+ - [L]
# maintenance rules
RewriteCond %{REMOTE_ADDR} !^23\.1\.12\.167
RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
RewriteCond %{REQUEST_URI} !\.(jpe?g?|png|gif) [NC]
RewriteRule .* /maintenance.html [R=302,L]
Letter case matters, so if you need to match mixed case spelling insert NC, into [OR].
You may consider adding slash / at the end of folder names if you have files in root folder with the same names.