Is it possible to force apache server to read root htaccess before going into subdirectory? - apache

I have a subdirectory in root (let's call it /sub) and .htaccess in root. If I call the following URL: mywebsite.com/sub, I get directly into subdirectory omitting .htaccess in root, so I wanted to ask whether it is possible to force server to read root .htaccess first before going to subdirectory (and make corresponding redirection if needed)?
Thanks in advance
EDIT: I have discovered that my redirection explicitly excluded directories which was unwanted (and seemed to be the root of my problem):
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) http://redirectwebsite.com/$1 [R=301,L]
I removed the second line, but unfortunately I still get into my folder.
So to make it clear:
when I go to http://mywebsite.com/not-a-folder-in-root, I am redirected to the new site correctly
when I fo to http://mywebsite.com/a-folder-in-root, I don't get redirected and go instead to my subfolder's index.php
The latter is the behavior I want to eliminate.

It depends on what you need to do. First .htaccess files are read in the order in which they are found.
How directives are read
The configuration directives found in a .htaccess file are applied to
the directory in which the .htaccess file is found, and to all
subdirectories thereof. However, it is important to also remember that
there may have been .htaccess files in directories higher up.
Directives are applied in the order that they are found. Therefore, a
.htaccess file in a particular directory may override directives found
in .htaccess files found higher up in the directory tree. And those,
in turn, may have overridden directives found yet higher up, or in the
main server configuration file itself.
So the htaccess file will always override the file in the root directory. However you can manipulate the Apache config file and specify directives in say a Location directive. You can specify certain rules and then it will take affect over .htaccess rule. See info below.
As discussed in the documentation on Configuration Sections, .htaccess
files can override the sections for the corresponding
directory, but will be overridden by other types of configuration
sections from the main configuration files. This fact can be used to
enforce certain configurations, even in the presence of a liberal
AllowOverride setting. For example, to prevent script execution while
allowing anything else to be set in .htaccess you can use:
<Directory "/www/htdocs">
AllowOverride All
</Directory>
<Location "/">
Options +IncludesNoExec -ExecCGI
</Location>
Otherwise if you can't do that change because you don't have access, you would have to do all the rules in the root .htaccess file that also pertains to the sub folder which you can do instead of putting an .htaccess in the sub folder.
Edit based on comment
#just use this for all requests
RewriteRule (.*) http://redirectwebsite.com/$1 [R=301,L]
#Or you can do all non-existent folders and that sub folder too
RewriteCond %{REQUEST_URI} ^/sub [NC]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) http://redirectwebsite.com/$1 [R=301,L]

Related

How to avoid the need of typing .php on the url?

I'm on MacOs Big Sur, using Apache and PHP. What I want is: not needing to put .php on the end of my files to load it.
For instance, instead of typing this on the URL:
127.0.0.1/public_html/home.php
I want just to type
127.0.0.1/public_html/home
To achieve this, I'm using this code in .htaccess:
RewriteEngine On
Options -Indexes
DirectoryIndex home.php index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L]
The code above works on my hosting, but for some reason, it does not work on my development machine. Instead, a get a 404 error.
The .htaccess file with the code is on the root of public_html folder.
What am I missing?
By typing some "nonsense" at the top of the .htaccess file and not getting an error (ordinarily you would get a 500 Internal Server Error) it would seem that .htaccess overrides were not enabled on the server. So, .htaccess files were effectively disabled - which they are by default on Apache 2.4.
To enable .htaccess overrides (to allow .htaccess to override the server config) you need to set the AllowOverride directive in the appropriate <Directory> container in the server config (or <VirtualHost> container). The default on Apache 2.4 is AllowOverride None.
With the directives as posted you would need a minimum of:
AllowOverride FileInfo Indexes Options
FileInfo for mod_rewrite, Indexes for DirectoryIndex and Options for Options and related directives.
Although it is common (and easier) to just set:
AllowOverride All
Reference:
https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [L]
These directives are not strictly correct. Whilst they may work OK for the URLs you are testing, they would result in a rewrite-loop (500 error response) if you simply append a slash to your URLs (and there is no directory by that name), eg. /home/ (or /home/<anything>). This is because your condition that tests for the presence of the .php file is not necessarily the same as the URL-path you are rewriting to. See my answer to the following question on ServerFault for a thorough explanation of this issue: https://serverfault.com/questions/989333/using-apache-rewrite-rules-in-htaccess-to-remove-html-causing-a-500-error
Also, there's no need to check that the request does not map to a directory to then check if the request + .php extension maps to a file. If the request maps to a file then it can not also be a directory, so if the 2nd condition is true, the 1st condition must also be true and is therefore superfluous.
And there's no need to backslash-escape literal dots in the RewriteCond TestString - this is an "ordinary" string, not a regex.
So, these directives should be written like this instead:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule (.+) $1.php [L]
(RewriteBase should not be used here.)
You can further optimise this by excluding requests that already contain what looks like a file extension (assuming your URLs that need rewriting do not contain a dot near the end of the URL-path). For example:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule !\.\w{2,4}$ %{REQUEST_URI}.php [L]
(With this 2nd version, it does not matter if RewriteBase is set - it is not used.)
DirectoryIndex home.php index.php
You gave an example URL of /public_html/home (to which .php is appended). However, this DirectoryIndex directive allows home.php to also be served when simply requesting the directory /public_html/. It should be one or the other, not both.

htaccess for laravel without affecting subdomains

I'm trying to get htaccess working for laravel 5.4, but without it affecting the sub-domains that are created.
My current htaccess
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
What I've tried is setting an htaccess in the sub-domain folders with the follwing:
RewriteEngine On
As I read elsewhere this should stop the top domain htaccess, yet when for example I have a sub-domain like dev.example.com, it will redirect to dev.example.com/dev
Anyway of getting rid of the /dev at the end?
Folder structure:
app
bootstrap
config
database
public
storage
resources
routes
dev --> subdomain
Upfront, I don't see how this /dev is related to the directives, you have shown. None of them do anything to add a /dev anywhere. Maybe it's just the subdirectory applied somehow.
The claim "this should stop the top domain htaccess" is not entirely true. From Apache - How directives are applied
The configuration directives found in a .htaccess file are applied to the directory in which the .htaccess file is found, and to all subdirectories thereof.
However, it is important to also remember that there may have been .htaccess files in directories higher up. Directives are applied in the order that they are found.
Therefore, a .htaccess file in a particular directory may override directives found in .htaccess files found higher up in the directory tree. And those, in turn, may have overridden directives found yet higher up, or in the main server configuration file itself.
So an .htaccess doesn't stop another .htaccess, but a directive overrides a directive. This means, you may have some directive from one .htaccess and another unrelated directive from the top level .htaccess.
In your case, RewriteEngine on just overrides RewriteEngine on from the main .htaccess file.
If you want to prevent any RewriteRule from the top .htaccess, I would rather try
RewriteEngine off

.htaccess - Redirect all to index.php for root folder or subfolder

I need an .htaccess file that will work whether it is put in the root folder or a subfolder without modification. The script below is the normal one that I've been trying to adapt without success. I tried the solution on htaccess rewrite index.php on root and subfolders and couldn't get it to work.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Layout
.htaccess
index.php
subfolder1
- .htaccess
- index.php
The route /blah should go to /index.php and /subfolder1/whatever should go to /subfolder1/index.php. Currently, the above script will send /subfolder1/whatever to /index.php.
[Update]
This should also work for any path under subfolder1, like /subfolder1/1/2/3/idunno.
If you are using Apache 2.2.16 and later, you can just stop using mod_rewrite, which although extremely useful and powerful, can get messy as hell.
A new directive in mod_dir was introduced, FallbackResource which does just that, redirecting to the uri of your choice if there is no hit on the file system. It is available in .htaccess files as long as AllowOverride Indexes is specified for the directories in the configuration.
As .htaccess files are evaluated depth-first, you just have to have each .htaccess file describe your fallback resource in the current directory, and the one in the subdirectory subfolder1 will take precedence:
subfolder1/.htaccess:
FallbackResource index.php
.htaccess:
FallbackResource index.php
They're both the same, and work just right.
It seems this directive is not well known yet even though it's been around for a few years, and its goal is precisely to solve that problem in an elegant way.
There is only one limitation with that setup. Calling urls in non-existing sub-directories of the root dir or subfolder1 will yield subrequest recursion and subsequently an error 500, because the fallback resource is local to the given directory.
The best approach is to have absolute uris (beginning with '/') as parameter to FallbackResource, which is why it is true that the requirement in itself is kind of odd, and is probably not playing too well with the inner workings of Apache.

Use mod_rewrite to create custom directory index in Apache

So, Apache's default directory listing sucks and mod_autoindex's customisation options suck, so I figured I could write some rewrite rules in my server root to redirect any requests to a directory:
<IfModule rewrite_module>
RewriteEngine on
RewriteCond %{REQUEST_URI} -d
RewriteRule .* /index.php?dir=$0
</IfModule>
Now, I get the impression this works at least a little, as turning off indexes still leaves localhost accessible (it displays the index.php), however it doesn't seem to reach subdirectories (which either revert to Apache's directory indexes if the indexes option is on, or give a 403 if they're off).
My question is: can I get this rule to apply globally or is my quest for pretty directory indexes doomed to failure?
Edit: I should note: the above rules are contained in a .htaccess in the server root.
Edit: Ideally the solution, if it exists, would still have DirectoryIndex functionality (that is, index.php etc. will be displayed if it exists),
The -d directory test does only work with absolute file system paths. So either provide an absolute file system path (e.g. by using %{DOCUMENT_ROOT}%{REQUEST_URI} or %{REQUEST_FILENAME} directly) or use -D that makes an additional subrequest to resolve the URI path to a file system path. I’d prefer:
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .* /index.php?dir=$0

How to fwd urls to existing paths AND one more path with apache's mod_rewrite?

My current .htaccess looks like this:
RewriteEngine On
# RewriteCond %{REQUEST_URI} !^/_project
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
# RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ index.php [QSA,L]
The uncommented lines are pretty straightforward:
The two Conds make sure the Rule isn't applied to existing files (!-f) and folders (!-d).
The Rule sends everyting else to index.php
The uncommented lines I took from somewhere. I believe it's the best way to do what I require: 'pretty urls'.
Basically it works. Existing files (e.g. /css/general.css) are requestable and non-existing paths (e.g. /admin/login) are routed to index.php. Existing and non-existing paths must be able to work 'amongst eachother': /css/all.css is sometimes a buffered existing css file and sometimes (when it doesn't exist) it's handled by PHP. /css/general.css is always a file. /css/club_N.css (N is a number) is always a PHP script.
/_project/ is an existing folder with Basic HTTP Auth protection. For instance /_project/phpinfo.php works as well. In the _project folder I have created a (valid) symlink to the backups folder: /_project/backups/. Somehow the (existing) files in the backups folder can't be reached. For instance /_project/backups/today.bz2 is routed to index.php =( The same happens with either or both commented lines uncommented.
What's wrong with the htaccess config? If I remove the Rewrite stuff entirely, I get a 403 Forbidden. Probably something with the .htaccess in the _project folder (?).
PS. Obviously I can't show you the actual website. People wouldn't like it if you could download their backups =)
.htaccess files are hierarchical in scope, any such files in parent directories apply to their children.
The Basic Auth in /_project/ will apply to subdirectories unless you switch it off in those directories, as will the RewriteRule declaration. Often it is wise to add RewriteEngine off in the .htaccess of the child directory structure to stop the rules applying there, or possibly add a conditional blocking that structure on the original rule set.