Rewrite Pretty or SEO friendly URL via htaccess - php

I have a problem with transforming urls from dynamic to static.
I have a site where different pages are generated with a dynamic url, like:
www.example.com/?pr=project-abc123
I would like to rewrite the url of each one with htaccess making it static, like this:
www.example.com/project-abc123
// or
www.example.com/pr/project-abc123
Now, i found this htaccess code that seems to work:
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} \?
RewriteCond %{QUERY_STRING} ^p=(.*)$
RewriteRule (.*) http://example.com/%1? [L,R=301]
RewriteRule ^(.*)$ /index/?pr=$1[L]
URLs are rewritten as indicated (first type, whitout /pr/ ), but gives me a multiple choice error. What am I doing wrong?

Let's understand RewriteRule directive which is the real rewriting workhorse.
A RewriteRule consists of three arguments separated by spaces. The arguments are
Pattern: which incoming URLs should be affected by the rule;
Substitution: where should the matching requests be sent;
[flags]: options affecting the rewritten request.
Let's start with the following snippet:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
First line of code, describes RewriteEngine is turned on. Here I use RewriteCond directive which defines a rewrite rule condition. Using RewriteCond directive we defined two conditions here. This directive took a server variable called REQUEST_FILENAME. The two conditions above tell if the request is not a file or a directory, then meet the rule set by RewriteRule. See more details on this issue.
Now it's time to write some rewrite rules. Let's convert
www.example.com/?pr=project-abc123
// to
www.example.com/project-abc123
and rewrite rule will be:
RewriteRule ^(.*)$ index.php/?pr=$1 [L]
And to get the www.example.com/pr/project-abc123 we need the rule as the below:
RewriteRule ^/?([a-z]+)/(.*)$ index.php/?$1=$2 [L]
// or
RewriteRule ^/?pr/(.*)$ index.php/?pr=$1 [L]
The [L] flag tells mod_rewrite to stop processing the rule set. This means that if the rule matches, no further rules will be processed.

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.

Cleanning urls with htaccess

i am trying to use RewriteRules to get clean urls using my HTACCESS file.
here is what i have so far
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
The above code takes a url that looks like this company.com/about.php and turns it into company.com/about/ so all my links url are like this "/about/" i didnt add the .php because of the rewrite rule.
what i am trying to do now is add a rule that will clean my url when parameter is passed. for example
company.com/about/?profile=member_name i want it to look like company.com/about/member_name
i have tried the two rewrite code below but it doesn't work.
RewriteRule ^([a-zA-Z0-9]+)$ /our_work.php/ [L]
RewriteRule ^/our_work.php([^/\.]+)/?$ ?project=$1 [L]
please keep in mind that my file extension is already being striped from the url.
Please help
Thank you in advance
Apache provides documentation on the use of RewriteRule that you should read before proceeding.
In this particular case, you can rewrite /about/{member_name} to /about.php?profile={member_name} by implementing this rule:
RewriteRule ^about/([a-zA-Z0-9]+)(/)?$ about.php?profile=$1 [L]
The rule states: The requested URL must begin with about/ and be followed by letters and numbers (match #1) and may be proceeded by an additional ending forward slash (match #2); and it will be substitued with a URL about.php with profile query string's value as match #1. The L flag indicates that any rules that follow this rule should be ignored.
Attempting to "cascade" rules will not work with your current set of rules because the /about/{...} is not matched by the first rule.

Rewriting url with one parameter out of multiple parameters in .htaccess

I have next lines in a htaccess file:
RewriteCond %{QUERY_STRING} (^|&)grp=([0-9]+)(&|$)
RewriteCond %{QUERY_STRING} (^|&)level=([0-9]+)(&|$)
RewriteRule ^alpe-adria/([a-zA-Z0-9_-]+)$ /site/index.php?d=1&box=1&grp=%1&grpname=$1&level=%2 [L]
The original URL has this code:
/site/index.php?d=1&box=1&grp=13&grpname=art-culture&level=1
The parameters d and box are fixed, other parameters grp, grpname and level are varying from page to page. What I want to do is to rewrite this URL into such state:
/alpe-adria/art-culture
So the problem is, how to single out grpname parameter and also use all other parameters, from which two are not fixed. I tried two RewriteCond %{QUERY_STRING} rules with no success. Idea is to single out two parameters and then use them in original URL. In other hand one parameter is used in original URL as in substitute URL. Again, I'm stuck and I need your precious help.
Whole snippet:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{QUERY_STRING} box=
RewriteRule ^alpe-adria$ /site/index.php [L]
RewriteCond %{QUERY_STRING} d=
RewriteRule ^alpe-adria$ /site/index.php [L]
RewriteCond %{QUERY_STRING} op=
RewriteRule ^alpe-adria$ /site/index.php [L]
RewriteCond %{QUERY_STRING} masterSearch=
RewriteRule ^alpe-adria$ /site/index.php [L]
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^alpe-adria/?$ /site/index.php?box=1&d=3 [L]
RewriteCond %{QUERY_STRING} (?:|.*&)grpname=([^&]*)
RewriteRule ^site/index\.php$ /alpe-adria/%1? [L,R]
Not very clear from your question but you can use a rule like this which makes your capture all these parameters grp, grpname and level from anywhere in query string:
RewriteEngine on
RewriteCond %{THE_REQUEST} \s/+site/index\.php\?d=1&box=1&grp=([^&]*)&grpname=([^&]*)&level=([^&]*) [NC]
RewriteRule ^ /alpe-adria/%2/%1/%3? [L,NE,R=302]
RewriteRule ^alpe-adria/([^/]+)/([^/]+)/([^/]+)/?$ /site/index.php?d=1&box=1&grp=$2&grpname=$1&level=$3 [L,QSA]
Do you really have such a non-SEO non-SEF URI coming in from a browser? What is the point of converting it to an SEF form like '/alpe-adria/art-culture'? Unless your new directory structure is actually set up that way, and you're trying to match old non-SEO/SEF URIs to the new layout.
Assuming you actually have incoming '/alpe-adria/*' URIs, you're not rewriting the original URL into /alpe-adria/art-culture. You're using .htaccess to rewrite /alpe-adria/art-culture (coming in from a browser) into the original format that PHP and the server can digest. Please use the correct terminology. .htaccess does nothing to outbound URIs.
You're saying that /alpe-adria/ is fixed, and you have a 'search engine friendly' group name (e.g., 'art-culture'). You want to map 'art-culture' into a URI for index.php? I can't see where you are getting the grp and level entries from in the incoming URI. The best you're going to be able to do is to have a number of lookup entries: match 'art-culture', output the desired full URI. Match something else, output the different desired full URI.

.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