Redirect (almost) all requests to the top level url - apache

I've looked at a lot of the other mod_rewrite questions here and tried most of them, but none seem to work for me. This is what I'd like to do.
Redirect all requests like http://abc.com/foobar to http://abc.com/
EXCEPT images and js, so requests like http://abc.com/images/foo/bar or http://abc.com/js/foo/bar
The URL bar should stay the same. So while http://abc.com/foobar loads http://abc.com/, the URL should read like the former
Ports should remain intact, so http://abc.com:8080/foobar should redirect to http://abc.com:8080
This is what I have in my .htaccess file
Options -Indexes
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/(images/.*|js/.*)$
RewriteRule ^(.*)$ - [L]
The condition is working well, and images and js files are loading fine. I thought the last line would redirect everything else to just the base domain, but I'm still getting 404 errors when I test it out.
I don't want to use a rule like this
RewriteRule ^(.*)$ http://abc.com/ [L]
because the domain may be different in different deployments.
I think I just have a poor understanding of how this works, but I'm just missing something small. Can someone help me get this sorted out?

This is what I ended up using
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/*|/index.html)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^[^\.]+$ index.html [L]
It's not perfect, because the last rule only looks for files without a dot (.) in them. So it will not apply to http://abc.com/images/image.jpg but will apply to http://abc.com/images.
I don't really understand why I have to do it this way, but it works as it does.

Related

apache RewriteRule not working

I have this url http://www.example.com/Courses/get/38789/my-course, i added this rule to the .htaccess file
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/Courses/get
RewriteRule ^Courses/get/(.*)/(.*)$ course-$1-$2 [R=301,L]
but when i go to http://www.example.com/Courses/get/38789/my-course nothing happens, i stay on the same page, there is no redirect.
p.s the link is just an example not the actual link
A more efficient method would be to use the following:
RewriteRule ^Courses/get/(\d+)/([^/]+)/?$ /course-$1-$2 [R=301,L]
Now, keep in mind that this rule should come before any rules that may rewrite the request to, say, an index.php file. This would be naturally true if the code you posted in your question was all of your code. If not, please post your entire .htaccess file so we can be sure it is being placed in the right location.
Be sure the mod_rewrite is turned on, and the you have set AllowOverride All in your virtual host/Apache site configuration. If you're running on a shared production server, this would not apply to you.
Side note: Whilst it does work, you need not use RewriteEngine on twice - only once at the beginning of your file will suffice. You also do not need RewriteCond %{REQUEST_URI} ^/Courses/get - it is essentially redundant as you are already using an expression to test against the request.

problems getting mod_rewrite working

I've not done much with mod_rewrite, but I can't seem to get anywhere with this. I'm wondering if perhaps it is not enabled on my server(even though my host says it is).
I have the following url: http://dev.website.com/folder1/translate/horse and I want that to redirect to: http://dev.website.com/folder1/translate.php?word=horse
My .htaccess starts with RewriteEngine on and I've tried various attempts to get it working, but no matter what, it just shows my home page (the default 404 redirect).
Things I've tried:
RewriteRule ^translate/.*$ translate.php?word=$1
RewriteRule ^translate translate.php
and some other things I don't remember, but I can't get anything to work.
The .htaccess file I am using is located in folder1. I have also tried putting random characters in the file to make it throw an error, and it does.
Anything I'm missing? How would I properly create this redirect?
As per request, this is my file structure.
I have the domain www.website.com, and a subdomain dev.website.com. The subdomain is set so that it redirects to www.website.com/dev. So, in this case, dev.website.com/folder1/translate.php = www.website.com/dev/folder1/translate.php. I am not sure how that masking is done, as it is accomplished via my web host's cpanel.
You aren't capturing $1 in brackets so this should work:
In DOCUMENT_ROOT/.htaccess:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^folder1/translate/(.*)$ /folder1/translate.php?word=$1 [L,QSA]
In DOCUMENT_ROOT/folder1/.htaccess:
RewriteEngine On
RewriteBase /folder1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^translate/(.*)$ translate.php?word=$1 [L,QSA]

Redirect all to index.php using htaccess

I am writing a simple PHP-based MVC-ish framework. I want this framework to be able to be installed in any directory.
My PHP script grabs the request uri and breaks it off into segments. It makes segment 1 the controller and segment 2 the action. This goes all fine when I do this:
http://www.example.com/mvc/module/test/
It will go to the specific module controller and method. Now I have a default controller, the home controller, which is in folder home.
Now when I access this folder directly http://www.example.com/mvc/home/
It will display a 403 forbidden , because this folder does exist, instead it should also go back to http://www.example.com/mvc/index.php
If I would have installed the framework in a different folder, lets say folder framework it has to redirect back to http://www.example.com/framework/index.php
I would like to redirect every folder and php file back to the index.php, leaving everything else the way it is.
My first problem I encountered was it never redirects to the right folder, always to the domain root folder.
This is what I tried :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
Your rewrite rule looks almost ok.
First make sure that your .htaccess file is in your document root (the same place as index.php) or it'll only affect the sub-folder it's in (and any sub-folders within that - recursively).
Next make a slight change to your rule so it looks something like:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
At the moment you're just matching on . which is one instance of any character, you need at least .* to match any number of instances of any character.
The $_GET['path'] variable will contain the fake directory structure, so /mvc/module/test for instance, which you can then use in index.php to determine the Controller and actions you want to perform.
If you want the whole shebang installed in a sub-directory, such as /mvc/ or /framework/ the least complicated way to do it is to change the rewrite rule slightly to take that into account.
RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]
And ensure that your index.php is in that folder whilst the .htaccess file is in the document root.
Alternative to $_GET['path'] (updated Feb '18 and Jan '19)
It's not actually necessary (nor even common now) to set the path as a $_GET variable, many frameworks will rely on $_SERVER['REQUEST_URI'] to retrieve the same information - normally to determine which Controller to use - but the principle is exactly the same.
This does simplify the RewriteRule slightly as you don't need to create the path parameter (which means the OP's original RewriteRule will now work):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
However, the rule about installing in a sub-directory still applies, e.g.
RewriteRule ^.*$ /mvc/index.php [L,QSA]
The flags:
NC = No Case (not case sensitive, not really necessary since there are no characters in the pattern)
L = Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)
QSA = Query String Append, just in case you've got something like ?like=penguins on the end which you want to keep and pass to index.php.
To redirect everything that doesnt exist to index.php , you can also use the FallBackResource directive
FallbackResource /index.php
It works same as the ErrorDocument , when you request a non-existent path or file on the server, the directive silently forwords the request to index.php .
If you want to redirect everything (including existant files or folders ) to index.php , you can use something like the following :
RewriteEngine on
RewriteRule ^((?!index\.php).+)$ /index.php [L]
Note the pattern ^((?!index\.php).+)$ matches any uri except index.php we have excluded the destination path to prevent infinite looping error.
There is one "trick" for this problem that fits all scenarios, a so obvious solution that you will have to try it to believe it actually works... :)
Here it is...
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [L,QSA]
</IfModule>
Basically, you are asking MOD_REWRITE to forward to index.php the URI request always when a file exists AND always when the requested file doesn't exist!
When investigating the source code of MOD-REWRITE to understand how it works I realized that all its checks always happen after the verification if the referenced file exists or not. Only then the RegEx are processed. Even when your URI points to a folder, Apache will enforce the check for the index files listed in its configuration file.
Based on that simple discovery, turned obvious a simple file validation would be enough for all possible calls, as far as we double-tap the file presence check and route both results to the same end-point, covering 100% of the possibilities.
IMPORTANT: Notice there is no "/" in index.php. By default, MOD_REWRITE will use the folder it is set as "base folder" for the forwarding. The beauty of it is that it doesn't necessarily need to be the "root folder" of the site, allowing this solution work for localhost/ and/or any subfolder you apply it.
Ultimately, some other solutions I tested before (the ones that appeared to be working fine) broke the PHP ability to "require" a file via its relative path, which is a bummer. Be careful.
Some people may say this is an inelegant solution. It may be, actually, but as far as tests, in several scenarios, several servers, several different Apache versions, etc., this solution worked 100% on all cases!
You can use something like this:
RewriteEngine on
RewriteRule ^.+$ /index.php [L]
This will redirect every query to the root directory's index.php. Note that it will also redirect queries for files that exist, such as images, javascript files or style sheets.
Silly answer but if you can't figure out why its not redirecting check that the following is enabled for the web folder ..
AllowOverride All
This will enable you to run htaccess which must be running! (there are alternatives but not on will cause problems https://httpd.apache.org/docs/2.4/mod/core.html#allowoverride)
just in case you were still wondering how to redirect all request either if the directory exists (for core framework folders and files) to the framework index handler, after some error/success attempts just noticed I just needed to change the RewriteCond in the .htaccess file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
the above condition states "not found files" and "not found directories", ok, what if just remove "not found" (!-d) line, and ended with something like the below:
RewriteEngine on
RewriteBase /framework/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /framework/index.php [L,QSA]
It worked for me like a charm
I just had to face the same kind of issue with my Laravel 7 project, in Debian 10 shared hosting. I have to add RewriteBase / to my .htaccess within /public/ directory. So the .htaccess looks a like
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
After doing that don't forget to change your href in,
home
Example:
.htaccess file
RewriteEngine On
RewriteRule ^about/$ /about.php
PHP file:
about

Mod_rewrite rules from root

This problem has been bugging me for a while now.
I have a created a small site engine and I'm using mod_rewrite to tell the engine what page to proccess, SEO friendly links is a bonus :).
This is how it's works today:
the adress http://www.example.com/site/page
becomes http://www.example.com/engine.php?address=page
But what i want is:
the adress http://www.example.com/page
becomes http://www.example.com/engine.php?address=page
Everything works fine if i create a psuedo directory for the calls (/site) but when i try to do the same from the root strange things start to happends.
RewriteBase /
RewriteRule ^site/(.*) engine.php?%{QUERY_STRING}&address=$1
Works fine: /site/about/contacts becomes eninge.php?address=about/contacts
RewriteBase /
RewriteRule ^(.*)$ eninge.php?%{QUERY_STRING}&address=$1
Doesn't work, for some reason /about/contacts becomes eninge.php?address=eninge.php
(.*) means catch anything. Have you tried exluding files and directory before your catch-all ? Because it will cause an infinite recursion without it.
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ eninge.php?%{QUERY_STRING}&address=$1 [L]
More information is available in the official documentation: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
Update: You should also specify [L] at the end of your rule, to tell Apache to end the rewriting process here.
Check the RewriteLog (this has been updated in 2.4, check current docs if not using 2.2):
RewriteLog "/usr/local/var/apache/logs/rewrite.log"
RewriteLogLevel 3
This will show you exactly what mod_rewrite is doing and allow you to tune your configuration based on its output. Beware - it grows very quickly, and should never be used in production environments.
As an aside, you have some typos in your post - worth verifying that these differ from your config.
RewriteCond %{REQUEST_FILENAME} !^engine.php
RewriteRule (.*) engine.php?address=$1 [QSA,L]
Try this. What you have is causing the rewrite to loop around and first do engine.php?address=about/contacts as you were expecting, but then go around again and rewrite that to engine.php?address=engine.php. Make sense? The [QSA,L] is a Query String Append and Last flag that will add the query string to your URL and tell the rewrite engine to stop looking for rewrites. The RewriteCond %{REQUEST_FILENAME} !^engine.php is to check that you haven't already specified the engine rewrite by ensuring the current URL doesn't start with engine.php. This is necessary if you are writing this in an .htaccess file rather than the .httpd config files.

How do I make .htaccess do what I want? :) (appending query string to url)

Currently my .htaccess looks like this...
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L,QSA]
It currently changes any /xxx.php file into /xxx. This is great for SEO. However, I also want Mr. htaccess to convert certain URLs into a URL + query string. For instance when user goes to
/specific/somerandominfo
Then somerandominfo is passed to the specific.php file. I normally have no problem doing this using rewrites, but because of my fancy catchall rewrite, I can't figure out how to do it.
For example if I add
RewriteRule ^specific/([^/]+)$ /specific.php?somerandominfo=$1 [NC]
to my .htaccess, then hitting up /specific/somerandominfo just serves me a big fat 500 Internal Service Error.
Any help from you apache gurus out there would be so, so cool.
Thanks!
p.s. anybody want to also throw in any other cool SEO tricks that they like? I'll bake you cookies.
You are getting 500 error because your rules are creating an infinite cycle. Check apache error log to see if it is true. So you should design your rules properly. Maybe like that:
RewriteRule ^([^/]*)$ $1.php [L]
RewriteRule ^(.*)/(.*)$ $1.php?var=$2 [L]
RewriteRule ^specific/([^/]+)$ /specific.php?somerandominfo=$1 [NC]
This is mostly correct. I'd just add the B flag, like this:
RewriteRule ^specific/([^/]+)$ /specific.php?somerandominfo=$1 [NC,B]
This causes the capture group $1 to be properly escaped for use in query strings. Note that you can still use QSA to retain the query parameters used in the original request (in addition to somerandominfo).
Perhaps you'll want to post your actual RewriteRule.