Pretty URL & SEO-friendly URL? - apache

I'm currently using Apache 2.2
I can do simple things like
RewriteRule ^/news$ /page/news.php [L]
RewriteRule ^/news/(.*)$ /page/news.php?id=$1 [L]
but what if I want to send 2 parameters like this
http://www.example.com/link/param1/param1_value/param2/param2_value
Lastly, I want to also know implementing SEO friendly URL like stackoverflow
though I can get access to a page with URL like
http://www.example.com/doc_no/
Just decorating that URL with
http://www.example.com/doc_no/this-is-the-article
Give me some suggestion with example snippets.

I know that the PHP symfony framework allows you to do that.
How does it work :
In apache config, use mod_rewrite to redirect ALL incoming resquest to a single entry point (in symfony this is called the "front controller")
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
In this front controller you are going to create a "Request" object which holds all the informations provided by the URL.
For example you could say that the first thing after the "/" is the name of the PHP file to call and everything else are parameters and values so that :
http://example.com/file/id/2 will call file.php with id=2
To do that, just use some reg exp and design you "Request" class carefully. For the example above the "Request" class should provide both getRequestedAction() and getParameter(string parameter) methods. The getRequestedAction() method will be used when the "Request" object is fully populated in order to call the correct file/action/method.
if you choose to populate the parameter array of the request object with both reg exp on the URL and a parsing of the _GET array, you may get to the point where :
http://example.com/file/id/2 is the same as http://example.com/file?id=2
(and both can work)
you can choose to ignore extensions (http://example.com/file.html is the same as http://example.com/file), or not.
Finally, for some URL, you can choose to just ignore everything that goes after the last '/'. So that : http://example.com/question/3/where-is-khadafi is the same as http://example.com/question/3/is-linux-better-than-windows
In the different file.php, just use $request->getParameter('id') to get the value of the "id" parameter, instead of using the _GET or _POST arrays.
The whole point is to
Redirect all incoming traffic to a single "front controller"
In that file, create a "Request" object that contains all the informations needed to run the site
Call the correct action (php file) based on the informations contained in that "Request" object
Inside the actions, use this request object to fetch the parameters contained in the URL
Hope this helps

Note Google have stated that they prefer news.php?id=$1 instead of news/$1 because it is easier for them to detect the variable. This is more pertinent when increasing the number of variables as just looking at your first example is a bit confusing:
http://www.example.com/link/param1/param1_value/param2/param2_value
You can always combine the two if one parameter is generic like a category:
http://www.example.com/param1/?id=param2_value
One should really reevaluate the design if more than one parameter is required and it is not a temporary search.

Related

htaccess files: Changing URL to username

In the following thread:
How to create user profiles with PHP and MySQL
I have a number of doubts:
In the first answer (by Chacha102) what is the '$1', I understand that it refers to a paramter but which one?
Does not the code in the first answer redirect to another index.php without renaming the url to something like www.facebook.com/username?
UPDATE:
Where does the edit to the url occur?
Doubt 1:
It refers to value of a get parameter user. For instance, if you have index.php?user=Name it refers to "Name".
Doubt 2:
The code wouldn't redirect. It will just rewrite url to www.domain.com/Name. It's equivalent to www.domain.com/index.php?user=Name.
1: The $1 is called the first captured group from the pattern. It refers to the value ?user=john (Read more about capturing groups)
2: In most of the PHP application the main entry (routing) point of http request is index.php. If you enter the url like http://www.example.com/john actually it would be the same as http://www.example.com/index.php?user=john if you have applied the same mod_rewrite rule from the answer.

Mod Rewrite on get vars

I'm working on a private project, which is basicly a profile system.
Now I've been trying how to improve the URL formatting.
At this moment, I am using URL's which look like:
-> http://example.com/overview
-> http://example.com/profile/?name=foo
-> http://example.com/jobs/?name=foo
Both overview and profile are directories on my website, which contain a single index.php file, which holds the PageID of which should be retrieved from the database.
Now, my goal is to format the URL to something as:
-> http://example.com/foo OR http://example.com/profile/foo
-> http://example.com/foo/jobs OR http://example.com/profile/foo/jobs
Is there anyway to do this with MOD_REWRITE?
This would mean the original url would look something like http://example.com/?character=foo/jobs which is http://example.com/get_var/directory.
I've done my research on Stackoverflow and Google, searching for 'mod_rewrite get variables'. But nothing seemed to be what I'd like to see happening.
Yours Sincerely,
Larssy1
To extract a portion of the URI between slashes and append it as a URL parameter, use the expression ([^/]+) to capture all characters up to but not including the next / into $1:
RewriteEngine On
RewriteRule ^profile/([^/]+)/([^/]+/?)?$ profile/$2?character=$1 [L]
The above rule will dynamically capture what follows Foo from your example, meaning that whether it was followed by /jobs or /other or /somethingelse, it would be appended as /profile/somethingelse?character=Foo. If that isn't necessary, and /jobs is static, you don't need to capture it into $2:
RewriteEngine On
# Don't dynamically capture what comes after the first variable group...
RewriteRule ^profile/([^/]+)/jobs$ profile/jobs?character=$1 [L]

Apache mod_rewrite path name as query parameters?

I want to use Apache's mod_rewrite in order to be able to take each folder of a path as a particular query parameter, for example consider the following:
Basic example
Url requested: http://domain.com/shoes/prada/image-1/
Page served: http://domain.com/?cid=shoes&bid=prada&pid=image-1
In this scenario, there are 3 sub-folders requested (/shoes/, /prada/ then image-1), so the first sub-folder is passed in the actual page served as cid, the second as bid and the third as pid.
Full example
However, I would also like it to serve a particular page depending on the number of sub-folders requested, e.g.
Url requested: http://domain.com/shoes/prada/
Page served: http://domain.com/shop.php?cid=shoes&bid=prada
So far all I've managed to find is regex based matching for mod_rewrite but my path's will vary a lot, which is why I would like to have conditions based on the number of folders accessed (please note, I'm not that good with regex - I reckon a wildcard character would help with this, but I wouldn't be sure where to start).
Any help on this would be greatly appreciated! This is pretty long winded, so if you need any more info for clarifying, please let me know!
With a little bit of work I was able to tweak some regex and get a working rule set for what I wanted:
RewriteEngine on
RewriteRule ^(.*)/(.*)/(.*)/(.)?$ product.php?tid=$1&sid=$2&eid=$3 [L]
RewriteRule ^(.*)/(.*)/(.)?$ brand.php?tid=$1&sid=$2 [L]
RewriteRule ^(.*)/(.)?$ shop.php?tid=$1 [L]
This is a bit different to the example, however it's what I intended for in the first place.
This allows for the rewriting of url's up to four folders deep, with the "name" of each folder being given as a parameter, and each additional level of depth rewriting the url to a separate resource for example:
http://x.com/shoes/prada/2011-high-heels/ -> http://x.com/product.php?tid=shoes&sid=prada&eid=2011-high-heels
Tested on http://martinmelin.se/rewrite-rule-tester/

Completely custom path with YII?

I have various products with their own set paths. Eg:
electronics/mp3-players/sony-hg122
fitness/devices/gymboss
If want to be able to access URLs in this format. For example:
http://www.mysite.com/fitness/devices/gymboss
http://www.mysite.com/electronics/mp3-players/sony-hg122
My strategy was to override the "init" function of the SiteController in order to catch the paths and then direct it to my own implementation of a render function. However, this doesn't allow me to catch the path.
Am I going about it the wrong way? What would be the correct strategy to do this?
** EDIT **
I figure I have to make use of the URL manager. But how do I dynamically add path formats if they are all custom in a database?
Eskimo's setup is a good solid approach for most Yii systems. However, for yours, I would suggest creating a custom UrlRule to query your database:
http://www.yiiframework.com/doc/guide/1.1/en/topics.url#using-custom-url-rule-classes
Note: the URL rules are parsed on every single Yii request, so be careful in there. If you aren't efficient, you can rapidly slow down your site. By default rules are cached (if you have a cache setup), but I don't know if that applies to dynamic DB rules (I would think not).
In your URL manager (protected/config/main.php), Set urlFormat to path (and toptionally set showScriptName to false (this hides the index.php part of the URL))
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName'=>false,
Next, in your rules, you could setup something like:
catalogue/<category_url:.+>/<product_url:.+> => product/view,
So what this does is route and request with a structure like catalogue/electronics/ipods to the ProductController actionView. You can then access the category_url and product_url portions of the URL like so:
$_GET['category_url'];
$_GET['product_url'];
How this rule works is, any URL which starts with the word catalogue (directly after your domain name) which is followed by another word (category_url), and another word (product_url), will be directed to that controller/action.
You will notice that in my example I am preceding the category and product with the word catalogue. Obviously you could replace this with whatever you prefer or leave it out all together. The reason I have put it in is, consider the following URL:
http://mywebsite.com/site/about
If you left out the 'catalogue' portion of the URL and defined your rule only as:
<category_url:.+>/<product_url:.+> => product/view,
the URL Manager would see the site portion of the URL as the category_url value, and the about portion as the product_url. To prevent this you can either have the catalogue protion of the URL, or define rules for the non catalogue pages (ie; define a rule for site/about)
Rules are interpreted top to bottom, and only the first rule is matched. Obviously you can add as many rules as you need for as many different URL structures as you need.
I hope this gets you on the right path, feel free to comment with any questions or clarifications you need

Abusing Mod Rewrite for a clean file system, and pretty URLs

I have a few php files that do a few different jobs. I'd like to change the way my clients access these php files to make it more clean for the end user. The Mod_Rewrite system has shown that it can do some pretty powerful things when in the hands of the right server admin. So I was wondering how far can you abuse the Mod Rewrite rules for a cleaner file system, and pretty URLs. Considering that the PHP files themselves use query strings to get their data, I'd like to alias the way the query string is built based upon how the how deep into the fake files system we go.
Our website's URL is http://www.domain.tld/, but we shall call it domain.tld for short. I'd like to map a few different address to a few different query strings on a few different files. But I'd also like to to be expandable on a whim.
Or first set would be, anything going past domain.tld/series/ should be directed to the domain.tld/series.php script with any (fake) directory past series to become part of the query-string for series.php. The same should happen to anything directed in the direction of domain.tld/users/ that should be redirected to the domain.tld/users.php file.
So if we had a URLs like, domain.tld/series/Master/2010/ or domain.tld/series/Novice/Season 01/ they would still be redirected to the domain.tld/series.php script, but with the query-string of ?0=Master&1=2010 and ?0=Novice&1=Season 01. But should I want to get an overview of the Master series, I could go the the URL domain.tld/series/Master/ and produce the query-string of just ?0=Master. The idea being that the rewrite rule should allow for infinite expandability.
This is how I'm doing it, and it sure works infinitely:
RewriteRule ^((/?[^/]+)+)/?$ ?q=$1 [L]
The trick is that the whole path is passed on as a single parameter, q, to index.php. So for example domain.tld/series/Novice/Season 01/ becomes domain.tld/?q=series/Novice/Season 01. Then you can do:
<?php
$params = explode('/', $_GET['q']);
var_dump($params);
?>
to get the individual parts.
array(3) { 0 => 'series', 1 => 'Novice', 2 => 'Season 01' }
It is not possible to be completely dynamic in such a system and have, as you say 'infinite expandability. You would have to define a RewriteRule for every 'tier' you will allow in your URL, or alternatively match everything after the first 'tier' as a single variable and do the work with PHP.
Example 1
RewriteRule ^([^/]+)/?$ /$1.php
RewriteRule ^([^/]+)/([^/]+)/?$ /$1.php?0=$2
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ /$1.php?0=$2&1=$3
Example 2
RewriteRule ^([^/]+)/(.*)/? /$1.php?qs=$2
Obviously these are only very simple examples and you'd probably have to use RewriteConds etc. to exempt certain files etc.