How to write .htaccess file to get everything after slash as parameter? - php

I have a URL i.e "www.mysite.com". I want to send parameters via url in following ways:
www.mysite.com/count
www.mysite.com/search_caption?query=huha
www.mysite.com/page=1
www.mysite.com/search_caption?query=huha&page=1
In each of these cases I want to load index.php page with parameters as follows for each case:
var_dump($_REQUEST) results into [count]
var_dump($_REQUEST) results into [query="huha"]
var_dump($_REQUEST) results into [page=1]
var_dump($_REQUEST) results into [query="huha",page=1]
How do I write .htaccess file to achieve this?
I am using this code but it is capturing only params after "?" and not everything after first slash
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^([^/]+)/?$ index.php?{REQUEST_FILENAME}=$1 [L,QSA]
RewriteRule .* /index.php [L]

Something like that should get close, though you really should think about those strange URL patterns instead of trying to fix them afterwards with rewriting...
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L,QSA]
RewriteRule ^count index.php?count=1 [L]
RewriteRule ^page/(.*)$ index.php?page=1 [L]
RewriteRule ^ index.php [L,QSA]
Some notes:
the first three RewriteRules are exceptions necessary because your given requests do not follow a sane and common pattern. They appear somewhat chaotically chosen.
this certainly is not free of issues, I did not test it, only typed it down.
this assumes the "page" example to be requested like as discussed in the comments.
index.php actually has to exist as a file, otherwise this will result in a rewrite loop
Given all that these rewritings should happen:
www.mysite.com/count => index.php?count=1
www.mysite.com/search_caption?query=huha => index.php?query=huha
www.mysite.com/page/1 => index.php?page=1
www.mysite.com/search_caption?query=huha&page=1 => index.php?query=huha&page=1
Also note that the rules above are written for .htaccess style files. To be used as normal rules, so inside the http servers host configuration, they would have to be written slightly different. You should only use .htaccess style files if you really, really have to, so if you have no access to the configuration files. You should always try to avoid those files if somehow possible. They are notoriously error prone, hard to setup and debug and really slow the server down. So if you have access to the http server configuration, then defines such rules in there instead.

Related

mod_rewrite REQUEST_FILENAME change after rule without L flag

I'm working on a .htaccess file and have come across some curious behavior with REQUEST_FILENAME that I'd love some clarification about. I have two rules I'm testing out which are like so:
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ /index.php [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/index.php$ /other_page.php [L]
When I try to go to the address site.com/this_file_exists.php I seem to be getting to other_page.php, which means that
REQUEST_FILENAME was a file in the first RewriteCond but not a file
by the time mod_rewrite processed the second RewriteCond.
After changing the second RewriteRule's flags to [L,E=RF:%{REQUEST_FILENAME}], and echoing $_SERVER['REDIRECT_RF'] on other_page.php, I find that the request filename was just /index.php, as opposed to the original filename, which was /full/path/to/this_file_exists.php.
Does mod_rewrite consistently overwrite the REQUEST_FILENAME in this way after matching a RewriteRule? If so, is there a documented way in which it does that?
These lines in mod_rewrite.c
/* Now adjust API's knowledge about r->filename and r->args */
r->filename = newuri;
seem to suggest that the new REQUEST_FILENAME truly is
the rewritten URI.

How to automatically make pretty urls

I have a site that I'm working on, but I'm annoyed that I have to work with ugly URLS. So, I have a URL of http://example.com/user.php?id=54 and another of http://example.com/foobar.php?name=Test.
How could I convert both of them to pretty URLS without adding it to .htaccess for every URL I want to make pretty?
example.com/user.php?id=54 => example.com/user/54
example.com/foobar.php?name=Test => example.com/foobar/Test
I have this in my .htaccess file:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f
RewriteRule ^([^/]+)/?$ $1.php [L]
RewriteRule ^$1/$3/? /$1.php?$2=$3 [NC]
Thanks,
Lucy
My full .htaccess file:
# include classes on every page
php_value auto_prepend_file Resources/Classes.php
# add custom Directory Indexes
DirectoryIndex index.php Default.php Down.php
# begin routing to pretty URLs
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^/(?!Resources)([0-9a-zA-Z-]+)/([0-9]+) /$1.php?id=$2 [NC]
RewriteRule ^/(?!Resources)([0-9a-zA-Z-]+)/([a-zA-Z-]+) /$1.php?name=$2 [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
Try this
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^user/([0-9]+) /user.php?id=$1 [QSA,L]
RewriteRule ^foobar/([0-9a-zA-Z-]+) /foobar.php?name=$1 [QSA,L]
if you want global rule you can make
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)/([0-9a-zA-Z-]+) /$1.php?parameter=$2 [NC]
or more specifically
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)/([0-9]+) /$1.php?id=$2 [NC]
RewriteRule ^([0-9a-zA-Z-]+)/([a-zA-Z-]+) /$1.php?name=$2 [NC]
when argument will be a string it will pas name parameter and when argument will be integer there will be id parameter passed.
I may delete this answer in the future as it might be specific to my setup.
I recently discovered, using Apache, that anything after the URL was populating the PATH_INFO environment variable. This means that given your example, example.com/user/54, if user was a script the server could process, anything after it would be populated into PATH_INFO; in this case it would look like /54. This is a great find because with proper structure, you could make your own router similar to Rails.
I would create some landing page (e.g., index) which is going to be your application router: example.com/index/<model>/<id>/. Inside index would be your routing code. I'll use Perl to demonstrate, since it's better than PHP :) Note that index could be called anything that Apache can process (e.g., router.php, index.pl, application.rb); though, removing the extension adds to the beauty of the URL.
index:
#!/usr/bin/perl
use 5.012;
# Retrieve what you're looking for; obviously not production-ready
my ($model,$id) = $ENV{PATH_INFO} =~ m{^/([^/]+?)/([^/]+)};
# route the request
given($model){
when('user'){ callUser($id); } # callUser defined elsewhere, perhaps another script
when('foobar'){ callFoobar($id); } # callFoobar defined elsewher, perhaps another script
default { makePageDefault(); }
}
http://example.com/index/user/1: passes 1 to callUser()
http://example.com/index/foobar/5: passes 5 to callFoodbar()
http://example.com/index/user: calls makePageDefault() because regex was not smart enough to handle anything without an ID
http://example.com/index/diffmodel/1: also calls makePageDefault(), since we don't handle diffmodel didn't exist
The script above is not production ready because it doesn't perform any sanitation and doesn't handle all the use cases you will need. My guess is you want something similar to Rails (e.g., example.com/movie/1/edit). While Apache is designed to handle the routing for you, there is some convenience in being able to manage this close to where your application code lives.
I have not implemented this method, so I'm curious to hear if this is something used and if there's any reason not to trust it.

htaccess Redirect Causes Errors

I'm working on a website that has been built sloppily.
The website is filled with regular links that are translated into the corresponding .php pages by the .htaccess page.
This is it:
RewriteEngine on
RewriteRule ^koral/(.*)/$ page.php?name=$1
RewriteRule ^koral/(.*)$ page.php?name=$1
RewriteRule ^(.*).html/(.*)/(.*)/(.*)$ cat.php?cat=$1&page=$2&order=$3&dir=$4
RewriteRule ^(.*).html$ cat.php?cat=$1
RewriteRule ^(.*)/(.*).html$ product.php?cat=$1&product=$2
<IfModule mod_security.c>
SecFilterEngine Off
</IfModule>
First of all, I would love some help regarding whether or not this page has everything it should. I've never messed with it before.
Secondly and my main issue, if, for example, I would write the address www.thewebsite.com/foobar.html, it would be translated into www.thewebsite.com/cat.php?cat=foobar by the .htaccess page, and it would give a database error (and reveal information about the database).
I've put a check into cat.php which checks if the category exists, but I can't redirect the user to the 404 error page. There's a page called 404.shtml in the website, but redirecting the user to it causes the .htaccess to just change it again to cat.php?cat=404.
Is the way they used the .htaccess page normal? Should I change this system?
And how are users sent to error pages? From what I understood the server should be doing it on its own?
I would love some clarification... There is some much about this subject I don't understand.
Update:
This is my new .htaccess page
RewriteEngine on
RewriteRule ^error.php?err=(.*)$ Error$1.html
# Only apply this rule if we're not requesting a file...
RewriteCond %{REQUEST_FILENAME} !-f [NC]
# ...and if we're not requesting a directory.
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^koral/(.*)/$ page.php?name=$1
RewriteRule ^koral/(.*)$ page.php?name=$1
RewriteRule ^(.*).html/(.*)/(.*)/(.*)$ cat.php?cat=$1&page=$2&order=$3&dir=$4
RewriteRule ^(.*).html$ cat.php?cat=$1
RewriteRule ^(.*)/(.*).html$ product.php?cat=$1&product=$2
<IfModule mod_security.c>
SecFilterEngine Off
</IfModule>
Because the redirecting is in the code and the user cannot see it, I allowed myself to write the link in a non-clean way. I tried turning it into a clean URL but the following does not do anything:
RewriteRule ^error.php?err=(.*)$ Error$1.html
Can someone please help me understand why? I thought since error.php is a real page, I should put it before the conditional but it didn't work. BTW, I saw in an article about .htaccess that the page should start with Options +FollowSymLinks. It seems to me that everyone sort of has their own way of writing it. Is there a guide or something like that, which I can be sure is authentic and covers all the bases there is about .htaccess?
Thank you so much!!
Using rewrite rules to work around links to .html pages that don't exist is unusual in my experience, but it's really just a different take on "pretty" URLs, e.g. www.thewebsite.com/foobar/ gets routed to cat.php?cat=foobar on the backend.
Your 404 issue is different. You need to be able to display error pages.
One option here is to rewrite requests as long as they don't request an existing file. This is very common for serving up static content like images, CSS files, and the like. To do this, you can use the -d and -f options to RewriteCond, which apply when requesting a directory and file respectively:
RewriteEngine On
# Only apply this rule if we're not requesting a file...
RewriteCond %{REQUEST_FILENAME} !-f [NC]
# ...and if we're not requesting a directory.
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^([^.]+)\.html$ cat.php?cat=$1 [L,QSA]
Now, requests to 404.shtml should go through, because you're requesting an existing file on the filesystem.
Note that the RewriteConds only apply to the single RewriteRule that immediately follows. For additional RewriteRules, also include additional RewriteConds.
Your regex is wrong anywhere. Literal dot needs to be escaped using otherwise it will match any character. Also it is better to use L and QSA flags to end each rule properly.
RewriteEngine on
RewriteBase /
RewriteRule ^koral/([^/]+)/?$ page.php?name=$1 [L,QSA]
RewriteRule ^([^.]+)\.html/([^/]+)/([^/]+)/([^/]*)/?$ cat.php?cat=$1&page=$2&order=$3&dir=$4 [L,QSA]
RewriteRule ^([^.]+)\.html$ cat.php?cat=$1 [L,QSA]
RewriteRule ^([^/]+)/([^.]+)\.html$ product.php?cat=$1&product=$2 [L,QSA]

.htaccess mod_rewrite: enabling caching via checking if file exists

I am implementing a caching system for dynamically generated images. The script is called via /img/type/param1/param2.png, where multiple types are possible and the number of parameters are variable. The script generates the image and dumps it to disk.
I would like .htaccess rules, which when requesting the image generation script:
checks to see if a cached file exists
if so, mod_rewrite to the cached file
if not, don't do anything so that the script runs
What I have so far is a slightly modified logic:
mod_rewrite to where the cached file would be
check to see if the file exists
if not, mod_rewrite the request back again
If there's a better way to do this, I'd love to hear it. In any case, the relevant part of my .htaccess file:
RewriteRule ^img/(type1|type2)/(.*)$ /images/cache/$1/$2
RewriteCond /^(.*)$ !-f
RewriteRule images/cache/(.*) /img/$1
This doesn't seem to work quite right. To debug it, I inserted the following after the first RewriteRule (the target page just dumps its input):
RewriteRule ^(.*)$ /htaccess.php?url=$1 [END]
As a result, I get:
Array
(
[url] => /images/cache/a/l/300.png/a/l/300.png
)
I don't understand why $2 contains l/300.png/a/l/300.png instead of just l/300.png.
If I change first RewriteRule to include an [L], I get the expected result. However, I experience the exact same "double-matching" issue on the second RewriteRule which reverts the request back into the non-cache version. However, adding [L] to this second RewriteRule:
RewriteRule ^img/(type1|type2)/(.*)$ /images/cache/$1/$2 [L]
RewriteCond /^(.*)$ !-f
RewriteRule images/cache/(.*) /img/$1 [L]
yields an Internal Server Error.
What am I doing wrong, and how do I fix this issue?
The first logic that you have is what you want to be doing, that bypasses the possible looping issues. You just need to extract the relevant bits from the %{REQUEST_URI} then backreference them using % references. So for example:
RewriteCond %{REQUEST_URI} ^/img/(.*)$
RewriteCond %{DOCUMENT_ROOT}/images/cache/%1 -f
RewriteRule ^img/(.*)$ /images/cache/$1 [L]
or using the regex patterns that you had:
RewriteCond %{REQUEST_URI} ^/img/(type1|type2)/(.*)$
RewriteCond %{DOCUMENT_ROOT}/images/cache/%1/%2 -f
RewriteRule ^img/(.*)$ /images/cache/$1 [L]

PHP & URL Rewriting

I need a little help figuring out what the following URL rewrite rule means. I can understant the first three lines, but I got stuck with the index.php/$1 part. What does exactly the / means in this rule? The only thing I would always expect to see after a file name would be a query-string separator (?). This is the first time I am seeing the / as a separator. What does it exactly mean?
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [PT,L]
</IfModule>
The <IfModule mod_rewrite.c>...</IfModule> block ensures that everything contained within that block is taken only into account if the mod_rewrite module is loaded. Otherwise you will either face a server error or all requests for URL rewriting will be ignored.
The following two lines are conditions for the RewriteRule line which follows them. It means that the RewriteRule will be evaluated only if these two conditions are met.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
These lines simply state that rewriting (RewriteRule line) will occur only if there are no existing files or folders on the server which match the URI. If they do exist then they will be served instead, unless there is some other directive that prevents it, otherwise rewriting will occur.
The last line will do the actual rewriting. It will take whatever is following the website domain name and append it to a rewritten request which will begin with index.php/.
Here is an example.
Lets say you make a request for example.com/example-page.html.
If there is no existing file or folder in the virtual hosts root folder named example-page.html the rewrite rule at the end will rewrite the request to look like example.com/index.php/example-page.html.
The main reason why applications rewrite requests like this is to ensure that they have a single point of entry, often called a bootstrap, which is considered to be a good practice from the security standpoint and also offers more granular control of requests.
Here is in my opinion a very good beginner friendly tutorial for mod_rewrite.
It's just rewritting the url name.
For example, this url:
http://www.example.com/something/else
Will be the same as:
http://www.example.com/index.php/something/else

Categories