htaccess rewrite url and check for 404 - php

I`ve got an internet shop and want to use htaccess to shorten links
there are 3 cases of urls:
shop.com/shop/18 (number) - products.php?categoryid=$1
shop.com/shop/18/page-2 (number)/(page+number) - products.php?categoryid=$1&page=$2
shop.com/shop/18/9877 (number)/(number) - description?categoryid=$1&productid=$2
my try
RewriteRule ^shop/?$ shop.php
RewriteRule ^shop/(.*)/([0-9]+)/?$ description.php?categoryid=$1&productid=$2
RewriteRule ^shop/(.*)/page-(.*)/?$ products.php?categoryid=$1&page=$2
RewriteRule ^shop/(.*)/?$ products.php?categoryid=$1
With my try - 1 (works), 2 (works), 3 (doesn`t work)
How can I rewrite urls so?
How can I redirect to 404 page if e.g. there is no such number of
category or such product (guess check with php and mysql and then
redirect) ?

There are a number of ways that this can be dealt with;
All in htaccess (gets messy with multiple depths)
Combined htaccess and server side code
The best approach is the one that suits you based on how your store is coded. I personally feel that handling it in the server side code is better, it simplifies the htaccess file, and gives you more control with regards to validating data, and how you handle what is sent, to where, and how its processed when it gets there.
For example, in my htaccess file I have;
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on
#
# Do not apply rewrite rules for non required areas
RewriteCond %{REQUEST_URI} "/hidden-areas/" [OR]
RewriteCond %{REQUEST_URI} "/other-areas/"
RewriteRule (.*) $1 [L]
# Do Not apply if a specific file or folder exists
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# The rules on how to rewrite the urls
RewriteRule (.*) /index.php?url=$1 [QSA,L]
</IfModule>
Basically, to explain this in a nutshell, I DONT rewrite anything for certain folders, I forward them straight on. This is to stop calls to scripts externally, or extra added systems being able to be accessed without issue.
I then, forward the entire url as a string through to my index page, and deal with what comes through using PHP, an example is below.
// collect the passed url
$url = $_GET['url'];
// split the url into parts
$url_parts = explode('/', $url);
/*
* start sorting what is what in the url
*/
// count how many parts there are
$url_parts_count = count($url_parts);
// determine the class/module
$class = $url_parts[0]; // generally the class/method/module depending on your system, thgough could be a category so run some checks
// determine the last part in the array
$last_url_part = ($url_parts_count - 1);
// set the last part of the url to be used
$slug = $url_parts[$last_url_part]; // generally the slug and will be empty if theres a trailing slash
etc etc etc
This is just a summary, i do far more, as this is taken from a CMS I wrote, but it should give you a very good starting point should you wish to get your hands dirty. Of course, Im happy to elaborate further if necessary.
The caveat of course, is if you are using an off-the-shelf system, they should provide you with this code already ;)
I have added below something based on your updated question, this will help if you do still plan to go the way you are :)
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on
RewriteBase /
#
# Do not apply rewrite rules for non required areas
RewriteCond %{REQUEST_URI} "/hidden-areas/" [OR]
RewriteCond %{REQUEST_URI} "/other-areas/"
RewriteRule (.*) $1 [L]
# Do Not apply if a specific file or folder exists
# RewriteCond %{REQUEST_FILENAME} !-f
# RewriteCond %{REQUEST_FILENAME} !-d
# The rules on how to rewrite the urls
RewriteRule ^([a-zA-Z0-9_-]+)$ /index.php?slug=$1 [QSA,L]
RewriteRule ^([a-zA-Z0-9_-]+)/$ /index.php?type=$1 [QSA,L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ /index.php?type=$1&slug=$2 [QSA,L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ /index.php?type=$1&cat=$2 [QSA,L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ /index.php?type=$1&cat=$2&slug=$3 [QSA,L]
</IfModule>

Thanks, ended with
RewriteRule ^shop$ shop.php [L]
RewriteRule ^shop/([0-9]+)$ products.php?categoryid=$1 [L]
RewriteRule ^shop/([0-9]+)/(page-[0-9]+)$ products.php?categoryid=$1&page=$2 [L]
RewriteRule ^shop/([0-9]+)/([0-9]+)$ description.php?categoryid=$1&productid=$2 [L]

Related

how to make a htaccess rule from id to name

I have a list of unique data:
Suppose I have the following data:
id name
1 Jhon
2 Peter
3 Mark
4 Scotty
5 Marry
I make a .htaccess rule for id:
RewriteRule brandlisting/(.*)/ site/brandlisting?id=$1 [L]
RewriteRule brandlisting/(.*) site/brandlisting?id=$1 [L]
my URL is:
http://localhost/mate/admin/site/brandlisting/3
this works for id.
Now I need a .htaccess rule for name, so I make a rule for it:
RewriteRule brandlisting/(.*)/ site/brandlisting?name=$1 [L]
RewriteRule brandlisting/(.*) site/brandlisting?name=$1 [L]
http://localhost/mate/admin/site/brandlisting/Mark
When I used the above URL I was faced with following error in the console:
"NetworkError: 400 Bad Request -
http://localhost/mate/admin/site/brandlisting/Mark"
and in browser it shows:
Error 400 Your request is invalid.
My current .htaccess file
RewriteEngine on
RewriteCond %{HTTP_HOST} ^localhost/mate/admin$ [NC,OR]
RewriteCond %{HTTP_HOST} ^localhost/mate/admin$
RewriteCond %{REQUEST_URI} !wordpress/
RewriteRule (.*) /wordpress/$1 [L]
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
#RewriteRule brandlisting/(.*)/ site/brandlisting?id=$1 [L]
#RewriteRule brandlisting/(.*) site/brandlisting?id=$1 [L]
RewriteRule brandlisting/(.*)/ site/brandlisting?name=$1 [L]
RewriteRule brandlisting/(.*) site/brandlisting?name=$1 [L]
I am starting with your current .htaccess you have crunch all the available rule which meets your needs in one single .htaccess for example rule for wordpress it should be in directory where your wordpress is installed.
Your rule as per your requirement should be like this if you are trying in root directory,
RewriteEngine on
RewriteBase /mate/admin/
RewriteRule site/brandlisting/([\d]+)/?$ site/brandlisting.php?id=$1 [L]
RewriteRule site/brandlisting/([a-zA-Z]+)/?$ site/brandlisting.php?name=$1 [L]
And for wordpress you directory you can create seperate .htaccess where you can put your rule index.php.
.htaccess rules rely on order. If you anticipate using a lot of routes, keep your htaccess rules simple and put your routes into PHP instead, using one of the several already written routing frameworks.
Here's an explanation as to why your .htaccess file isn't working, line-by-line:
RewriteEngine on
This turned the RewriteEngine on. No problems so far.
RewriteCond %{HTTP_HOST} ^localhost/mate/admin$ [NC,OR]
RewriteCond %{HTTP_HOST} ^localhost/mate/admin$
RewriteCond %{REQUEST_URI} !wordpress/
Only match RewriteRule is it's WordPress. This seems to be working, so let's ignore this block of rules.
RewriteRule (.*) /wordpress/$1 [L]
Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Only match below if the requested filename is not a file or a directory.
RewriteRule .* index.php/$0 [PT,L]
Rewrite any path PATH to index.php/PATH. Stop processing if it matched (note the L as last). That means nothing below will be activated.
#RewriteRule brandlisting/(.*)/ site/brandlisting?id=$1 [L]
#RewriteRule brandlisting/(.*) site/brandlisting?id=$1 [L]
RewriteRule brandlisting/(.*)/ site/brandlisting?name=$1 [L]
RewriteRule brandlisting/(.*) site/brandlisting?name=$1 [L]
Assuming that it doesn't match .* (aka, never), check path for other patterns. Note also that the two lines you have commented, and the two lines you don't, both match the same pattern. If one worked, the other would not.
-- Pro Tip: Regex has a shorthand for including a rule with a trailing slash and without one: /? is equivalent to, either with one slash, or with no slashes. Another way to write this is /{0,1}.
How to Fix
.htaccess redirect rules are a pain. My rule of thumb is to make them as easy as possible to write, which makes them easy to read and to maintain. How to do this? Push the redirect logic to your PHP program, rather than forcing Apache to rely on it.
Solution 1
The htaccess-only approach here would be to ensure you understand what Apache rewrite flags are telling your server to do, and adjust accordingly. You can do this here one of two ways:
Make your more specific rules show up first. i.e., move /site/brandlisting?name=$1 rules to before .* rules.
Add a separate rewrite conditions for any followup processing. As per the Apache2 documentation linked above:
The [L] flag causes mod_rewrite to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the last command in Perl, or the break command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules.
The key point here is that it is within each rule set. Building a new rule set will continue processing.
Example that should work (not tested):
RewriteEngine on
RewriteCond %{HTTP_HOST} ^localhost/mate/admin$ [NC,OR]
RewriteCond %{HTTP_HOST} ^localhost/mate/admin$
RewriteCond %{REQUEST_URI} !wordpress/
RewriteRule (.*) /wordpress/$1 [L]
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
#New Rule Set
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Note that /? is the same as writing two separate rules,
# one with a slash at the end, and one without.
RewriteRule brandlisting/(.*)/? site/brandlisting?name=$1 [L]
There are some great pre-built routers out there, like Silex and Slim. If you don't want to use them, you can still use your own internal logic that parses various pieces. From my experience, the more that I can pull out of my .htaccess file, the happier you'll be. It winds up being far easier to debug issues, and it's easier to iterate changes without introducing unintended consequences.
Solution 2
You can use PHP routers in conjunction with the .htaccess file I provided above, like so:
// Slim example
$app = new Slim\Slim();
$app->get('/brandlisting/:key', function ($key) {
if (is_numeric($key)) {
$id = $key;
// call/run $id logic
} else {
$name = $key;
// call/run $name logic
}
});
// ...
$app->run();
If you do this, you can remove any of your brandlisting logic from .htaccess and instead put it into your index.php.
Conclusion
If you can help it, experience tells me that it's better to not write your app logic into .htaccess rules. Instead, make your .htaccess rules simple and use a routing library. If you want to use .htaccess, make sure you understand the Apache rewrite flags you're using, and that Apache reads everything from top to bottom. For example, if the [L] flag is used, Apache stops reading all other rules in the rule set. That means, you have to create a new rule set with additional rules that need to be processed, or put your more specific rules first. Keep in mind that, if those rules have an [L] flag, they will also stop execution of any subsequent rules.
You can use redirect here.
Assuming you have the following folders:
<server root>/mate/admin
place in .htaccess in mate/admin
RewriteBase /mate/admin/
RewriteRule "site/brandlisting/([^\\]+)/" "site/brandlisting?id=$1" [R,L]
RewriteRule "site/brandlisting/([^\\]+)" "site/brandlisting?id=$1" [R,L]
You may be running into an issue where a Directory or other directive is causing your rewrite rules to repeatedly fire and cause infinite redirects.
See the documentation for RewriteRule Flags: L.
Specifically, the following quoted text is relevant:
If you are using RewriteRule in either .htaccess files or in
sections, it is important to have some understanding of
how the rules are processed. The simplified form of this is that once
the rules have been processed, the rewritten request is handed back to
the URL parsing engine to do what it may with it. It is possible that
as the rewritten request is handled, the .htaccess file or
section may be encountered again, and thus the ruleset may be run
again from the start. Most commonly this will happen if one of the
rules causes a redirect - either internal or external - causing the
request process to start over.
It is therefore important, if you are using RewriteRule directives in
one of these contexts, that you take explicit steps to avoid rules
looping, and not count solely on the [L] flag to terminate execution
of a series of rules, as shown below.
You may need to add a rewrite condition or take other steps to prevent looping.

.htaccess rewrite all URLs, even if path

I've made some PHP code that will direct the user based on the URL, and I've found some code for htaccess that gives the URL to the index page which lets my code work. However, it's also technically revealing what is a file/folder and what isn't.
If I go to website.com/somethingrandom/somethingelse, I'll get a 404 error, whereas going to website.com/cache/private will say forbidden.
How would I edit it so that it will act like no files exist, aside from a few select file types, such as images, css, and js files?
Here is the code as it currently stands:
RewriteBase /
RewriteEngine On
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-f
# This rule converts your flat link to a query
RewriteRule ^(.*)$ index.php?_page_location=$1 [L,NC,NE]
Have your rules like this:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L,NC]
# add trailing slash to directories
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]
# If the request is not for known file types
RewriteCond %{REQUEST_URI} !\.(?:jpe?g|gif|php|bmp|png|ico|tiff|css|js)$ [NC]
# This rule converts your flat link to a query
RewriteRule .* index.php?_page_location=$0 [L,QSA]
If you want to hide some file or directory, i.e. appear it as not existant, you might redirect with the R|redirect flag
RewriteRule ^cache/private - [R=404,L]
This tells the client, there is no such file named cache/private (404). Beware though, that this is for all clients, even yourself.
To restrict this, you must prefix the rule with some RewriteCond or wrap it in some conditional statement like If or similar.
If you want to hide all files, use a "broader" regular expression, like
RewriteRule ^ - [R=404,L]
This will return a "Not found" for all of your website's URLs. You can also give a set of URLs, like in this
RewriteRule ^(?:cache/private|secrets|database) - [R=404,L]
which will hide everything below
cache/private
secrets
database
See Apache - Regular Expressions and http://www.regular-expressions.info/ for details on how to customize your own pattern.

.htacces url_rewrite difficulties

I have a problem with the configuration of the .htaccess of small website that I'm working on.
I want all pages to be redirected to index.php?page=REQUEST and that file will find in the database the content for the requested page.
The problem occurs when I have installed a forum, so I want these forum pages to redirect to the index.php?page=forum&params
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} /(.*).html
RewriteRule ^(.*)forum/category/(.*)?$ index\.php?page=forum&lang=$1&category=$2 [L]
RewriteRule ^(.*)/(.*)(\.html?)$ index\.php?lang=$1&page=$2 [L]
RewriteRule ^(.*)(\.html?)$ index\.php?page=$1 [L]
Evetything works fine, except the forum part. How do I need to change the .htacces?
RewriteEngine on
RewriteRule \.(jpg|png|gif|svg|css|js)$ - [L]
RewriteRule ^(.*)/forum/topic/(.*)?$ index\.php?page=forum&lang=$1&topic=$2 [L]
RewriteRule ^(.*)/forum/category/(.*)?$ index\.php?page=forum&lang=$1&category=$2 [L]
RewriteRule ^(.*)/(.*)(\.html?)$ index\.php?lang=$1&page=$2 [L]
RewriteRule ^(.*)(\.html?)$ index\.php?page=$1 [L]
The problem appears to be that your RewriteCond is matching requests that end in .html. As your forum URLs don't end in .html the condition for the subsequent RewriteRule is never met.
There are some other possible problems too:
^(.*)forum will match www.url.com/en/ when it looks like you probably just want en
category/(.*) will match any characters, including forward slashes and the like. Presumably you just want it to match a decimal identifier.
Links to things that aren't covered by your rewrite config e.g. images
I'd probably rewrite your config to look something like this (N.B. not tested in Apache; only in a regex debugger):
RewriteEngine on
# only match forum URLs
# e.g url.com/en/forum/category/12345
RewriteCond %{REQUEST_URI} ^/.+/forum/category/[0-9]+
RewriteRule ^/(.+)/forum/category/([0-9]+) index.php?page=forum&lang=$1&category=$2 [L]
# match all URLs ending in .html
# e.g. url.com/en/foo.html
# and url.com/foo.html
RewriteCond %{REQUEST_URI} ^/.+\.html$
# a bit complicated, this matches both
# /apage.html
# /folder/apage.html
RewriteRule ^(?:/(.+))?/(.+)\.html$ index.php?lang=$1&page=$2 [L]
The second RewriteRule should always provide a value for page but only provide a value for lang if the URL is of the form /lang/page.html. This should be OK if your index.php file can accept an empty lang parameter or supply a default value.
Alternatively, if you don't mind keeping your existing regex and it's only images, CSS etc you want to bypass in URL rewriting you can add some rules at the start to skip them e.g.
RewriteEngine on
# don't actually rewrite, and stop processing rules
RewriteRule \.(jpg|png|css|js)$ - [L]
# only match forum URLs
# e.g url.com/en/forum/category/12345
RewriteCond %{REQUEST_URI} ^/.+/forum/category/[0-9]+
RewriteRule ^/(.+)/forum/category/([0-9]+) index.php?page=forum&lang=$1&category=$2 [L]
etc...

.htaccess / php url rewriting without routing?

So I've been searching for a while now and can't find anything specific on how to create a pretty url / seo / slug url type system WITHOUT sending everything to a index.php or moving things into subfolders.
Basically I'm making a website which you can currently go to urls like movie.php?id=#### / show.php?id=####. Ideally I'd like the url to be movie/#### or movie/id/#### (or down the line slugs of the name that i can use to grab the right one) etc.
Is there a way to do it without having a single index.php router or am I just going to have to rewrite all my files to adhere to this style?
You can create a rewrite rule in .htaccess that routes the movie urls to movie.php as follows:
movie/123:
RewriteRule ^movie/(\d+)$ movie.php?id=$1 [L]
movie/id/123:
RewriteRule ^movie/id/(\d+)$ movie.php?id=$1 [L]
movie/title-of-movie:
RewriteRule ^movie/(\S+)$ movie.php?slug=$1 [L]
movie/title/title-of-movie:
RewriteRule ^movie/title/(\S+)$ movie.php?slug=$1 [L]
combination movie/123/title-of-movie:
RewriteRule ^movie/(\d+)/(\S+)$ movie.php?id=$1&slug=$2 [L]
Edit: added a full .htaccess example for 1 required with up to 2 extra optional parameters with a fallback on index.php if the url is not for movies.
Options -Indexes
IndexIgnore */*
Options FollowSymLinks
AddDefaultCharset utf-8
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^movie/([^/]+)/?([^/]*)/?([^/]*)$ movie.php?param1=$1&param2=$2&param3=$3 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . index.php [L]
</IfModule>
^ to match from the beginning
$ to match until the end
? for 0 or 1 occurrence
+ for 1 or more occurrences
* for 0 or more occurrences
If the url rule does not match and the file does not exist then it will route the url to index.php, but you can remove that last part if you don't want that.
Yes, assuming your URL structure follows a relatively consistent pattern, you can definitely do this with an .htaccess file and mod_rewrite (without the need for an index.php file, commonly referred to as a front controller).
Here's a really simple example:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)/(.*)$ $1.php?id=$2 [NC,L]
This takes an incoming URL like http://example.com/movie/3 and performs a transparent/internal rewrite (so the user doesn't see the URL change) to http://example.com/movie.php?id=3.
Of course, this example could be expanded to handle more parameters, etc. but hopefully this gets you started on the right path. I highly recommend you read the mod_rewrite documentation for more details: http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

.htaccess mod_rewrite check if querystring var is avail

Basically I want to rewrite my urls so that it is website.com/folder/ sometimes though I need it to rewrite also website.com/folder/page/
Currently I have it working with just the website.com/folder/ but can not get it to check if there is a page, if I create just another rule under the folder one it reads that one, and gives me an empty page var, which is breaking my php. I struggle with .htaccess and any help would be appreciated.
Here is what I have that works with just the folder but I can not include a page.
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/?(css|js|images|html|docs)/
RewriteRule ^([^/]*)/$ /?folder=$1 [QSA]
Here is what I tried to get it to work with either just a folder, or a folder and page
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/?(css|js|images|html|doc)/
RewriteRule ^([^/]*)/$ /?folder=$1 [QSA]
RewriteCond %{REQUEST_URI} !^/?(css|js|images|html|doc)/
RewriteRule ^([^/]*)/([^/]*)/$ /?folder=$1&page=$2 [L,QSA]
Please Help!
Accordingly to the RewriteRule docs you should reverse the rules order in your rules set. Because in your configuration both rules have the same RewriteCond, the most specific rule (folder + page) should be atop and the most general rule should be the last one. If not when the first rule is matched the URL is rewritten and the second rule never matches. Also, probably you want to remove the trailing forward slash in the pattern of your folder + page rule (assuming that the second group in the pattern matches a page not a folder). So I think the whole thing should read:
RewriteCond %{REQUEST_URI} !^/?(css|js|images|html|doc)/
RewriteRule ^([^/]*)/([^/]*)$ /?folder=$1&page=$2 [L,QSA]
RewriteCond %{REQUEST_URI} !^/?(css|js|images|html|doc)/
RewriteRule ^([^/]*)/$ /?folder=$1 [L, QSA]

Categories