Mod_rewrite and MySql - mod-rewrite

I have a url eg. www.example.com/user.php?user_id=9 , where the user_id field maps to one of the pk in the user table . I don't want the url to be like this , instead i want to have a url like www.example.com/user/Aditya-Shukla.i am using apache 2 and I understand that mod-rewrite module has sets of rewriting rules which can be used to create url alias.
My question is
I have all href in the form www.example.com/user.php?user_id=9. So to change the url I suppose i have to change all the href's to the www.example.com/user/Aditya-Shukla and for rewriting the rule do a query to get a record?
Is there a better solution .

No, mod_rewrite does not have sets of rewriting rules. It rather provides directives to build rules based on regular expression patterns that can be combined with additional conditions.
In your case you would build a rule that takes any requested URL path that starts with /user/ and has another path segment following and rewrites it internally to your user.php, like:
RewriteEngine on
RewriteRule ^/user/([^/]+)$ /user.php?name=$1
The first directive RewriteEngine on is just to enable mod_rewrite. And the second directive RewriteRule … is the rule as described above: ^/user/([^/]+)$ is the pattern that matches any URL path that starts with /user/ (i.e. ^/user/) and that is followed by one path segment (i.e. ([^/]+)$). That request is then rewritten internally to /user.php while the matched path segment behind the /user/ is used as a parameter value for the name parameter ($1 is a reference to the matched value of the first group denoted with (…)).
So this will rewrite a request of /user/Aditya-Shukla internally to /user.php?name=Aditya-Shukla. You can then use that user name and look it up in your table.

You can either add a RewriteRule that will rewrite user/Aditya-Shukla to user.php?user_name=Aditya-Shukla and handle the rest in your code.
RewriteEngine On
RewriteRule ^user/(.*)$ user.php?user_name=$1
Or using a RewriteMap directive to lookup usernames, which will allow to rewrite user/Aditya-Shukla directly to user.php?user_id=9

I presume that within your own site you will always create the canonical form of the URL, i.e.:
/user/Aditya-Shukla
...and you are just having to deal with outside links that are not in canonical form, i.e. "old links" like:
www.example.com/user.php?user_id=9
mod_rewrite may not be suitable for remapping in this situation. I am presuming you may have very many users, and that number may grow. mod_rewrite does have a RewriteMap directive and yes there are ways to generate your map dynamically, but I don't think that would be a good design (to dynamically create a map of userId-to-userName dynamically every time your rewrite rule matches...)
Instead you should simply write your user.php code to lookup the correct userName, assemble the canonical form of URL you want, and send a redirect back to the client. Something like:
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://www.example.com/user/Aditya-Shukla" );
You should probably also use a 301 redirect (instead of 302) to indicate this is a "permanent" URL change, which will help search bots index your site correctly if it encounters an "old style" URL out there.
-broc

Related

Set a custom url for Codeigniter Controller

Please can any one suggest how to shorten the url
http://localhost:8080/MyWebApp/index.php/Cpanel_control/
to
http://localhost:8080/MyWebApp/Cpanel
in Codeigniter using routes.
I tried it in this way
$route['Cpanel'] = "MyWebApp/index/Cpanel_control";
But did not work
To remove index.php from your url in CI, you need .htaccess file.
Check this out https://gist.github.com/philipptempel/4226750
I'm assuming Cpanel_control is a valid controller.
For the routing, you can have this in your routes settings
$route['Cpanel'] = "Cpanel_control";
To avoid any other issues, make sure base_url in config file is set thus
$config['base_url'] = "http://localhost:8080/MyWebApp";
New Approach
Routing:
In some instances, however, you may want to remap this relationship so
that a different class/method can be called instead of the one
corresponding to the URL.
A short excerpt from the CI doc shows that you can't use routing here. Instead you should go for a mod_rewrite rule (.htaccess)
RewriteEngine On
RewriteRule ^index/Cpanel_control/(.*) Cpanel/$1 [R]
Old approach
According to the corresponding documentation, the paths are both not absolute. Furthermore, you need to set the "from"-URI as the array key and the "to" URI as the string. If you want to route index/Cpanel_control to Cpanel, you need to swap the URIs of you example.
So this would be correct:
$route['index/Cpanel_control'] = "Cpanel";

mod_rewrite take part of url and add it to the end of a second url

I am attempting to make it where faculty or students at my library that have a pmid number for PubMed, and want to share the link with others could do it by just remembering our url, and adding the pmid to the end of our url, with the identifier p.
This is where mod_rewrite comes in it would drop off the url: site.com/p/112233444 but keep 112233444 and then add it to the end of linkresolver.com/112233444
The rule that I have come up with is:
RewriteRule ^/p/(.*)$ linkresolver.com=$1
First, is this possible I control the library domain, but I am not in control of the second url that I am attempting to add the PMID to.
Second, this is my first attempt at mod_rewrite so if I am way let me know I have looked at Apache's documentation. I know it is really powerful complex tool, so my rewrite rule just seems off.
Any help would be greatl
Does this work?
RewriteRule ^p/(.*)$ http://linkresolver.com/$1 [R]

Mod Rewrite - hide .php, hide optional querystring

I figured out how to hide .php, but I need to hide any query string on the URL, and provide for there not being one.
Here's my current rule: RewriteRule ^/?([a-z]+)$ $1.php
I've searched everywhere, to no avail.
Lets say you have a page that displays items from some kind of a lookup. So the requested resource is www.example.com/page.php?display=news.
In this case you can use something like RewriteRule ^/news/$ page.php?display=news This way you can create friendly URLs for different resources which might need a query string value passed in.
Lets say you want to make this generic. So display can have values news, about, company which map to the urls /news/ /about/ /company/ then you simply change your rule to
RewriteRule ^/([^/]+)/?$ page.php?display=$1
You can also use this second method to say change your shopping cart system's URLs to a friendly one. Say your shopping cart uses a query string like - shop.php?category=1&product=10. You can convert this into a URL like shop/category/1/product/10. The rule would be
RewriteRule ^shop/category/([^/]+)/product/([^/]+)$ shop.php?category=$1&product=$2

Replacing the "X" in this url www.websitename.com/info.php?lid=X

Help please.
I am looking for the best way to replace the "X" (number) in this url
www.websitename.com/info.php?lid=x
the "x" is a numerical value - i would like to replace the "X" with the "name" field from my database.
Is mod rewrite the way to go? I have multiple urls of the same format (different "X" value of course at the end) that i wish to change to create more friendly urls by replacing the "X" with the corresponding value from the database field "name".
If mod rewrite is the way to go can anyone help out with recommended code to go in the htaccess?
Thanks in advance.
Totally edited: My previous answer was based on a misunderstanding of what you're trying to ask.
What you are asking is to create a friendly URL system. This is covered in many tutorials -- just search for "friendly URLs" and you'll find lots of resources.
Here's a summary of how it works...
To create friendly URLs for your site, you would need something like this in .htaccess (not sure if I got the RewriteRule right because this is completely off the top of my head, so google for a full-blown tutorial to verify):
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule /info/(.+) /info.php?name=$1
</IfModule>
This means a request to http://www.example.com/info/foo would be rewritten to http://www.example.com/info.php?name=foo.
Then you need to modify your application (in particular, the info.php file) to handle this new request format in which the name is given in the URL instead of the id.
Note that in this example, all names (e.g., "foo") must be unique. If any two items in your database have the same name, you're going to have problems. With this in mind, you might want to add a new field to your database table, which is a unique column containing a string using only alphanumeric characters and hyphens appropriate for use in a URL (this type of string is called a slug). You will basically use this slug instead of the id for database queries. Let's say you create an item named "The Discombobulator". When this item is created in your application, it should also create a slug along the lines of "the-discombobulator" and ensure it's unique. If you create a second item also called "The Discombobulator", your app might generate a slug for it like "the-discombobulator-2".
So, when someone requests http://www.example.com/info/the-discombobulator-2, mod_rewrite changes that to http://www.example.com/info.php?name=the-discombobulator-2 and hands it to your app. Your app gets the name parameter, which is "the-discombobulator-2" and looks that up in the database's slug field, and gets the matching record.
I think this is what you are looking for:
http://www.roscripts.com/Pretty_URLs_-_a_guide_to_URL_rewriting-168.html

How can I handle dynamic URIs where all segments are arbitrary?

How can push a URI like this in CodeIgniter (1.7.1 currently):
example.com/seg1/seg2/seg3/seg4/
or
example.com/seg1/seg2/
etc. through a single class method in a controller whose name does not appear in the URI? In a regular PHP scenario I would use mod_rewrite something like this:
RewriteRule ^([^/]+)/$ myfile.php?one=$1 [L]
RewriteRule ^([^/]+)/([^/]+)/$ myfile.php?one=$1&two=$2 [L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/$ myfile.php?one=$1&two=$2&three=$3 [L]
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/$ myfile.php?one=$1&two=$2&three=$3&four=$4 [L]
(I sanitize and validate the segments extensively in PHP, returning 404 if invalid)
But in Codeigniter I can't figure out how to do this without hard coding at least the first segment, but then using custom routes it still wants to treat the subsequent segments as method calls.
I'm a newbie to CI, but have so far managed to port over the entire existing site with the exception of this part of it. I don't see how all the parts come together on this problem, so any suggestion is welcome.
Clarification: I read through documentation on URI library, routing etc before starting my project, and they were helpful for various things, but this specific problem is not addressed by any of them. I'm not seeing how all segments of the URI can essentially be funneled through a controller that is not named in the URI and where all segments are arbitrary. The routing examples assume you know the value of the first segment. I already know how to remove "index.php" as well as access segments.
Have you looked up URI routing in the user guide and the wiki? They should tell you almost anything about routing, rewriting and accessing the different URI segments.
http://codeigniter.com/user_guide/general/routing.html
http://codeigniter.com/user_guide/libraries/uri.html
http://codeigniter.com/wiki/mod_rewrite/
[Edit:]
Here's the long description:
There is no way to not "hard-code" the first segment, and you can still "hard-code" the second segment.
What you want to accomplish can be nearly done by editing the routes in system/application/config/routes.php:
$route['(:any)'] = 'your_default_controller/index/$1';
$route['default_controller'] = "your_default_controller";
So, the first segment of your URI will be the method of the controller. You can access all segments of your (initial) URI by
$this->uri->segment(n)
You would then use the method index to call the desired function for each request.
On a side note: Why do you want to use an MVC framework for that, as you do not use much of the benefits of MVC?

Resources