How to reference the current directory from .htaccess using mod_rewrite? - mod-rewrite

I'd like to use mod_rewrite to make pretty URLs, but have a single version of the .htaccess file that can be used for any user on a server.
So far I have the standard pretty URL .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
Ideally, I would like something similar to
RewriteRule ^(.*)$ %{URL of this file's directory}/index.php/$1 [L]
This documentation would lead me to believe that what I want is not necessary:
Note: Pattern matching in per-directory context
Never forget that Pattern is applied to a complete URL in per-server configuration files. However, in per-directory configuration files, the per-directory prefix (which always is the same for a specific directory) is automatically removed for the pattern matching and automatically added after the substitution has been done. This feature is essential for many sorts of rewriting - without this, you would always have to match the parent directory which is not always possible.
I still get the wrong result, though, whether or not I put a leading / in front of the index.php on the RewriteRule.
This,
http://server/test/stream/stream
turns into
http://server/index.php/stream
not
http://server/test/index.php/stream
when the .htaccess file is in /test/.

I was having a similar problem, but found that simply leaving off the root '/' resulted in my test web server (xampp on windows) serving a URL similar to:
http://localhost/C:/xampp/htdocs/sites/test/
Not perfect. My solution is to use a RewriteCond to extract the path from REQUEST_URI. Here's an example for removing the unwanted "index.php"s from the end of the URL:
RewriteCond %{REQUEST_URI} ^(.*)/index.php$
RewriteRule index.php %1/ [r=301,L]
Note: the percent sign in "%1/", rather than a dollar sign.
%1-%9 gets the patterns from the last matched RewriteCond, $1-$9 gets the patterns from the RewriteRule.
See:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond
Cheers :)

Turns out that it does matter whether I put a leading / in front of index.php or not. By leaving it off, the script works correctly. I had been testing with the R flag which was using physical directories on the redirect.

Related

Mod_Rewrite for URL

I have been looking through questions and answer for days trying to figure out how to make this work.
So far I can get my URL to change, but it won't load the page.
I have to take
http://www.mysite.com/index.php?mode=about
And have it show up as
http://www.mysite.com/about/
So far I have the following code:
RewriteEngine on
RewriteCond %{QUERY_STRING} ^mode=(.*)
RewriteRule ^ http\:\/\/\www.mysite.com\/%1? [R=301,L]
RewriteRule /(.*) /index.php?mode=%1 [L]
I have changed things multiple times and nothing. Most site seem to tell me I don't need the 301 redirect but then I can't get anything to work.
For (your) example, once you've properly routed from mysite.com/index.php?mode=about to mysite.com/about, it's now going to look at mysite.com/about/ to find what comes next (index.py/index.html/etc).
Because there is nothing at /about/, you're getting a 404 error.
I don't think you can use mod_rewrite to do exactly what you're trying to achieve, without having some handling within /about/ to actually display the page you want once you get there.
http://www.noupe.com/php/10-mod_rewrite-rules-you-should-know.html
Remember the Filesystem Always Takes Precedence
The filesystem on your server will always take precedence over the
rewritten URL. For example, if you have a directory named “services”
and within that directory is a file called “design.html”, you can’t
have the URL redirect to “http://domain.com/services”. What happens is
that Apache goes into the “services” directory and doesn’t see the
rewrite instructions.
To fix this, simply rename your directory (adding an underscore to the
beginning or end is a simple way to do that).
I have to take
http://www.mysite.com/index.php?mode=about
And have it show up as
http://www.mysite.com/about/
There are two very common types of rules that people want and your statement can be interpreted two ways which require different rules. I'm going to interpret your statement that you have a real, operational script at http://www.mysite.com/index.php?mode=about, but instead of having the user enter that "ugly" URL, you want them to be served that URL when they enter http://www.mysite.com/about/. To accomplish this, you would do the following:
RewriteRule ^about/?$ /index.php?mode=about [L]
Because of the potential for misunderstanding, it's best to state what you want as (1) What the user will enter into their browser and (2) what real file you want to serve them.
I don't believe you need lines #2 & 3 & you seem to have % instead of $, try:
RewriteEngine on
RewriteRule ^([^\/]+) /index.php?mode=$1 [L]
Solved the problem. Thanks for all the help.
#< IfModule mod_rewrite.c>
# RewriteEngine on
# RewriteCond %{REQUEST_FILENAME} !-f
# RewriteCond %{REQUEST_FILENAME} !-d
#< /IfModule>
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?mode=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?mode=$1
You can use this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [L]
RewriteRule ^([^/]+)/$ /index.php?mode=$1 [L]
Where the beginning still allows for other folders to be accessible.

mod_rewrite - trouble with combination of rules

I've got the following rules to work which:
only act on files that exist
exclude any files that contain images|js|css in their uri
add trailing slash to request uri
Rewrite rules:
RewriteEngine on
DirectorySlash Off
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/(images|js|css)$
RewriteRule ^(.*[^/.])$ /$1/ [R=301,L]
I now need to correctly redirect my home uri's like so:
http://www.example.com/sitemap/ -> http://www.example.com/index.php?page=sitemap
I've tried the following approach:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/.])$ index.php?page=$1 [R=301,L,NC]
But I get a page not found, presumably because $1 is being fed something with a slash in it. I thought [^/] would remove it but apparently not.
Could someone explain where I am going wrong here please?
Use this rule -- it will rewrite /sitemap/ into /index.php?page=sitemap:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ /index.php?page=$1 [QSA,L]
Put it into .htaccess into website root folder. If placed elsewhere it need to be tweaked a bit.
URL will stay the same. Existing query string will be preserved.
The trailing slash / must be present (i.e. /sitemap will not trigger this rule).
It will only rewrite if there is no such folder or file (i.e. if you have a folder named sitemap in your website root folder then no rewrite will occur).
It will only work for 1-folder deep URLs (e.g. /sitemap/, /help/, /user-account/ etc). It will not work for 2 or more folders in path (e.g. /account/history/).
RE: this line: RewriteCond %{REQUEST_URI} !/(images|js|css)$.
You said you want "exclude any files that contain images|js|css in their uri". Unfortunately the above pattern work differently -- it will match /something/css but will not match /css/something or /something/file.css.
If you want to match images|js|css ANYWHERE in URL straight after a slash, then remove $.

Rewrite Rule(s) for domain aliases

Situation: I have a single (main) domain, which has several aliased domains, each of which are pointing at the same Plesk-based server (for instance, I have example.com as main, with something.net, anotherone.co.uk, and several others all as aliases of the main domain account). This means that whenever I enter the domain name into my address bar of any of the aliases, it goes directly to the account of the main domain (example.com).
Problem: Based on the domain name of the alias(es), I have an index.php that redirects each domain differently (for instance, requests to domain A redirects to a corporate site, domain b goes to a thanks site etc.) Which works great, but if a directory is added after the domain URL (i.e. somealias.com/something) then it gives a 404 not found error.
What I would really appreciate, if someone can help me out, is a (single if possible) rewrite ruleset that would essentially strip off ALL trailing directories and/or GET requests, and only leave the typed-in base URL, so then the php script sitting in the main domain document root can take over and deal with the request appropriately.
Strangely enough, I've not been able to find a (simple) solution for this anywhere. Is it a case of having to define a rule for each of the aliased domains individually?
Try the following,
#Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.olddomain.com$[OR]
RewriteCond %{HTTP_HOST} ^olddomain.com$
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !=/
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule .* http://%{HTTP_HOST}/? [L]
This will take ALL requests except root folder / (e.g. http://example.com/) or index file (e.g. http://example.com/index.php) and redirect them to the root folder (e.g. http://example.com/some-url will be redirected to http://example.com/).
You may need to replace index.php by the file that is get executed when you hit the root folder (Apache will silently rewrite http://example.com/ to http://example.com/index.php (depending on your actual settings) as it needs to have a file to execute otherwise it may show an error).
Alternatively (possibly even better -- depends on your actual setup and requirements) you may use these rules -- this will redirect only non-existing URLs. So if you have an image meow.png on your site, these rules will allow you to access it (http://example.com/meow.png):
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* http://%{HTTP_HOST}/? [L]
UPDATE:
If you going to place this into config file (httpd-vhost.conf or httpd.conf) then use these rules:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteCond %{REQUEST_URI} !=/index.php
RewriteRule .* http://%{HTTP_HOST}/? [L]
It seems to me that all the sites are hosted on the same server (probably using the same code base).
If your index.php is a front controller you can redirect everything to your index.php and decide in the first lines of index.php what front controller to load (like backend.php).
If you don't mind having to maintain a list of the aliases you can define a hash of [alias] => path-to-front-controller.
In the front controller of you main domain you check the alias name (using $_SERVER['SERVER_NAME'] for example) against the hash and load the appropriate file.
You will have to add and entry to the hash each time you add anew alias. If they are not generated dynamically maintaining this hash is not a lot of hassle.

mod_rewrite: redirect to a folder with the same name as domain

I have a bunch of domains pointing to the same folder, the root of my host "public_html".
I wish I could redirect them, each one for a folder with the same name as the domain.
eg: redirect www.mydomain.com to "public_html/www.mydomain.com"
I tried this:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/%{HTTP_HOST}/.*$
RewriteRule ^(.*)$ /%{HTTP_HOST}/$1 [L]
But with no success. What's wrong?
Its even possible to redirect to folder that uses a 'dot' on its name?
Thanks in advanced.
The test pattern in your RewriteCond is actually trying to match input starting with the literal string /%{HTTP_HOST}/. The value of the %{HTTP_HOST} variable is not expanded like you were expecting, so the condition will always be true (the pattern itself will never match). You'll need to modify the RewriteCond, and there are a few different approaches.
If this is the only rewrite you perform, you can just check to see if you've done it yet:
RewriteCond %{ENV:REDIRECT_STATUS} =""
Or, if the resource won't exist until you rewrite it, you can check for that instead:
RewriteCond %{REQUEST_FILENAME} !-f
Finally, you can mimic your original condition by using backreferences within the test pattern, along with a separator character that won't appear in your URL:
RewriteCond /%{HTTP_HOST}/#%{REQUEST_URI} !^([^#]+)#\1
Note that this doesn't guarantee that you've done the redirection though, it only ensures that the request URI has the host name as its first path segment. However, that's generally good enough.

Mod-rewrite shenanigans

I have this rewrite rule
RewriteEngine On
RewriteBase /location/
RewriteRule ^(.+)/?$ index.php?franchise=$1
Which is suppose to change this URL
http://example.com/location/kings-lynn
Into this one
http://example.com/location/index.php?franchise=kings-lynn
But instead I am getting this
http://example.com/location/index.php?franchise=index.php
Also, adding a railing slash breaks it. I get index.php page showing but none of the style sheets or javascript are loading.
I'm clearly doing something very wrong but I have no idea what despite spending all day R'ingTFM and many online primers and tutorials and questions on here.
Your problem is you are redirecting twice.
'location/index.php' matches the regex ^(.+)/?$
You want to possibly use the "if file does not exist" conditional to make it not try mapping a second time.
RewriteEngine on
RewriteBase /location/
RewriteCond %{REQUEST_FILENAME} !-f # ignore existing files
RewriteCond %{REQUEST_FILENAME} !-d # ignore existing directories
RewriteRule ^(.+)/?$ index.php?franchise=$1 [L,QSA]
And additonally, theres the [L,QSA] which tries to make it the "last" rule ( Note, this is not entirely obvious how it works ) and append the query string to the query, so that
location/foobar/?baz=quux ==> index.php?franchise=$1&baz=quux
( i think )
It sounds to me as though the rewrite filter is executing twice. Try adding a last flag
RewriteRule ^(.+)/?$ index.php?franchise=$1 [L]
Your rule self matches, and therefore it will reference itself.

Resources