Using mod_rewrite to substitute variable used in URL - php

I've gone through a few different questions like:
Rewrite for all URLs
Can mod_rewrite convert any number of parameters with any names?
Creating dynamic URLs in htaccess
Which helped me change one set of urls from domain.com/script2.php?d=1 to domain.com/(d), but now I'm stuck with something that I can't find an answer for. Currently, I have a set of URLs that are set up as:
domain.com/script.php?a=1
While I know how to change those URLs to domain.com/(a) this doesn't quite help me with this one because variable A is just a numerical identifier, so going from domain.com/script.php?products=1 to domain.com/1 doesn't do me a lot of good.
Instead, it's variable B which is actually the descriptor, ProductName. So what I'm trying to do is have it so that rather than domain.com/(a), I can get domain.com/(b). There is a complication. The reason that the original set up used variable A is that multiple products use the same descriptor in variable B, so I also need to include variable C which differentiates them, so I need the URL to be domain.com/(b)-(c).
Bonus! Remember how I said I had another script that I'd changed from domain.com/script2.php?d=1 to domain.com/(d)? Well, it'd be super awesome if I could set up my this current script to display not as domain.com/(b)-(c) but instead as domain.com/(d)/(b)-(c) because domain/(d) is actually the search page for this other script, so it's a really logical flow and would really simplify browsing, and would let users intuitively move between the search and the products without much work.
I have no idea if this is even possible, but any help would be appreciated.

Why not just rewrite everything back to your script file?
RewriteEngine on
RewriteBase /
RewriteRule .* index.php [L]
Will rewrite everything back to index.php. From there you can parse the $_SERVER['REQUEST_URI'] variable in PHP. From there you can decide what page to load based on the given url.
If you have any other folders in the same directory of the rewrite rule above, you can put another .htaccess file inside those that have RewriteEngine Off if you don't want them to be rewritten back to index.php. That is what you will need for a css file or site images.
Using this method, you could always do something like this.
domain.com/products/1
or, domain.com/search/blahblah

Related

Create a rewrite rule in .htaccess for php file

I am very new to .htaccess, I am having some problem with file action.
Example:
http://www.domain.com/upload_pic.php?action=save_pic
I wrote the .htaccess rule like
RewriteEngine On
RewriteRule ^sabc([a-zA-Z0-9!##$-_]*)$ upload_pic.php?action=$1
I want the desired result like:
http://www.domain.com/sabc/save_pic
How can I get the desired result, please correct my .htaccess line.
Change it to:
RewriteEngine On
RewriteRule ^sabc/(.+)$ upload_pic.php?action=$1
The .+ will capture one or more characters after the / and be captured into $1
There are several other guides on the web already, but to understand it in better way as you are beginner #AMY, I have writen this for you. Hope this will work for you.
Most dynamic sites include variables in their URLs that tell the site what information to show the user. Typically, this gives URLs like the following, telling the relevant script on a site to load product number 7.
http://www.domain.com/upload_pic.php?pic_id=7
The problems with this kind of URL structure are that the URL is not at all memorable. It's difficult to read out over the phone (you'd be surprised how many people pass URLs this way). Search engines and users alike get no useful information about the content of a page from that URL. You can't tell from that URL that that page allows you to buy a Norwegian Blue Parrot (lovely plumage). It's a fairly standard URL - the sort you'd get by default from most CMSes. Compare that to this URL:
http://www.domain.com/sabc/7/
Clearly a much cleaner and shorter URL. It's much easier to remember, and vastly easier to read out. That said, it doesn't exactly tell anyone what it refers to. But we can do more:
http://www.domain.com/sabc/user-navnish/
Now we're getting somewhere. You can tell from the URL, even when it's taken out of context, what you're likely to find on that page. Search engines can split that URL into words (hyphens in URLs are treated as spaces by search engines, whereas underscores are not), and they can use that information to better determine the content of the page. It's an easy URL to remember and to pass to another person.
Unfortunately, the last URL cannot be easily understood by a server without some work on our part. When a request is made for that URL, the server needs to work out how to process that URL so that it knows what to send back to the user. URL rewriting is the technique used to "translate" a URL like the last one into something the server can understand.
To accomplish this, we need to first create a text document called ".htaccess" to contain our rules. It must be named exactly that (not ".htaccess.txt" or "rules.htaccess"). This would be placed in the root directory of the server (the same folder as "upload_pic.php" in our example). There may already be an .htaccess file there, in which case we should edit that rather than overwrite it.
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^sabc/?$ upload_pic.php [NC,L] # Handle requests for "sabc"
A couple of quick items to note - everything following a hash symbol in an .htaccess file is ignored as a comment, and I'd recommend you use comments liberally; and the "RewriteEngine" line should only be used once per .htaccess file (please note that I've not included this line from here onwards in code example).
The "RewriteRule" line is where the magic happens. The line can be broken down into 5 parts:
RewriteRule - Tells Apache that this like refers to a single
RewriteRule.
^/sabc/?$ - The "pattern". The server will check the URL of every
request to the site to see if this pattern matches. If it does, then
Apache will swap the URL of the request for the "substitution"
section that follows.
upload_pic.php - The "substitution". If the pattern
above matches the request, Apache uses this URL instead of the
requested URL.
[NC,L] - "Flags", that tell Apache how to apply the rule. In this
case, we're using two flags. "NC", tells Apache that this rule should
be case-insensitive, and "L" tells Apache not to process any more
rules if this one is used.
# Handle requests for "sabc" - Comment explaining what the rule does (optional but recommended)
The rule above is a simple method for rewriting a single URL, and is the basis for almost all URL rewriting rules.
RewriteEngine On
RewriteRule ^sabc/(.+)$ upload_pic.php?action=$1
Hope this will be helpful for you to understand URL rewriting #AMY.

A Dynamic website using PHP

I am a beginner PHP programmer. I searched google for a "Dynamic PHP website tutorials". I found some stuff. They use $_GET variable to make the website dynamic, so the URL's appear like this:
example.com/?page=home
example.com/?page=about
example.com/?page=Downloads
and so on...
But most of the dynamic websites that I found on the internet has links like this:
example.com
example.com/about
example.com/download and so on....
So how do they do so ?? Have they got folders for all the catogories ?? And Also some websites have article URLs (eg : example.com/articles/posts/2010/article1.php). It would be a reall mess if they've got folders for all items. If not then How ?? Can someone give an example please ?
If you're using apache then read: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
If you're using IIS then read: http://www.iis.net/downloads/microsoft/url-rewrite
In order to use the $_GET variable, it must be in the query string (or being routed through some other means that isn't 'default').
For example, the URLs you're using would become.
example.com/?page=home
example.com/?page=about
example.com/?page=Downloads
Additionally, you can rewrite URLs using the .htaccess file (http://httpd.apache.org/docs/2.0/misc/rewriteguide.html)
You are interested in page routing.
htaccess and MVC routing may start you down the correct path :)
To echo everyone else, it's called a url rewite.
For example, the url
http://example.com/index.php?ext=blog&cat=news&date=12122012
can be rewritten as
http://example.com/blog/news/12-12-2012
This isn't automatic, it requires defining the patterns used for understanding the new URL in a file called .htaccess which usually resides in the servers root directory. Note that the preceding '.' in the filename makes it a hidden file.
When I was first getting used to PHP i found the site http://phpbuilder.com a great help. They have a lot of articles, and a forum that is fairly nice to noobies. http://devshed.com is a good site too, and has a large amount of information on subjects outside of PHP.
You can achieve that affect with folders, but most use rewrites (Apache). It's a bit too broad of a subject to go in to here, but if you just search for rewrite tutorials you'll find some pretty quickly.
The $_GET is only to get variables from the URL. While this can be used to make sites dynamic, this is a technique which is usually frowned upon.
With rewrites, you basically have a URL like /about, but the rewrite tells your server something like "act like this is actually ?page="about"), which you then use the $_GET to process.
Being PHP beginner I will not urge you to use .htaccess, As you will need to learn lot many things before you proceed further. You have 2 option to send a request one is GET and POST. You can get more information about same on internet.
Also you have an option to start your dynamic website using CMS and I will recommend you to use wordpress. CMS will have some in-built function which will help you to do your work faster. Also using their control panel you can update the URL format.
I will also urge you to go step by step and follow every tutorial that you will find on internet.
All the best
If you want to do this you have to use .htaccess file and have to load mod_rewrite in your apache server.
In you root directory create file named .htaccess
Then Write:
RewriteEngine On
RewriteRule ^(.*)\.php$ index.php?page=$1 [L,QSA]
And After that call a page
my-page.php
It will redirected as a index.php?page=my-page internally but in browser it will show as my-page.php

htaccess sequential redirection

I'm new with the htaccess redirection, and I'm having some trouble with how it works, I think that is because I need something a little bit different.
I want this
http://localhost/webroot/type_enduro-cross-trial/brand_yamaha/
to be redirected to
http://localhost/webroot/search.php?type=enduro-cross&trial=brand_yamaha
I use that values as filters from products; but the original URL is generated in two steps.
Example:
The user goes to the main page (http://localhost/webroot), and wants to filter by type, so when he clicks, the filter is applied and the URL changes to http://localhost/webroot/type_enduro-cross-trial and it works!
But I want the user to be able to add more filters, so now he wants to filter by some brand, and when he click the URL changes to http://localhost/webroot/type_enduro-cross-trial/brand_yamaha/. And so on with more filters.
This rewrite rule works to obtain the value of the first parameter:
RewriteRule ^([^_/]+)_([^_/]+)/([^_/]*) search.php?$1=$2 [L]
But when I add more filters, it clearly ignore them, and I have no idea of how must the rewrite rule should be.
Thanks, and sorry for my English!
What you want to achieve is non-trivial to do with .htaccess. Instead of solving this complicated within .htaccess just only leave a single rule inside the file and do the work inside your search.php script. This allows you a greater flexibility.
Just pass everything as a single parameter to the php script, like:
RewriteRule /pages/(.+) /page.php?page=$1 [QSA]
In your php script you do some string processing on $_GET['page'] (exemplary from the example RewriteRule above), e.g. by using explode.
Inside PHP you can far better work with arrays, something you can not at all inside the .htaccess file.
Examples have been taken from the original Apache HTTP Mod_Rewrite documentation.

sef url with php or .htaccess

Hi i want to make safe urls for a website. I used php's explode function that way
$explode = explode("/",$_SERVER['REQUEST_URI']);
I then was extracting with $explode[2] etc the names inside the url and then with sql statements combined them with the db took ids, names and whatever else. Entered url was like
http://www.example.com/index.php?var1=value1&var2=value2&var3=value3
and made it
http://www.example.com/value1/value2/value3 through .htaccess.
Code there is
RewriteRule ^(.*)/(.*)/(.*)$ index.php?var1=$1&var2=$2&var3=$3 [L]
But the site's php is already written fully so i do not want to change all GET queries at url cause now are not working. Is there an easier way to do so or can you correct the code so i can use again GET functions above? I forgot to mention at url value1,value2 etc are not ids (numbers) but the corresponding names. For example if it is for a furniture the url is
www.example.com/furniture/chair/.. not www.example.com/3/24/...
Is there any other way to succeed this functionality? Thanks.
I'd say you might also be looking for something like
PHP dynamic DB page rewrite URL
Which will gather any and all variables from a URL and you can use them accordingly from there on in. It would be using htaccess and a similar logic to what your wanting to do, less the rewrite rule the way you have it now.

php based website that displays page content based on URL?

I would like to make a website that is php and only requires one php document to display the content. It's kinda hard to explain, so let me try my best.
Some websites use a directory based system such as this:
web.URL.com/index.htm
web.URL.com/about.htm
web.URL.com/blog.htm
and so on.
This involves creating a text file for each page.
So, the goal here is to create one page that acts like a frame, and displays content based on the Url, so it will be acting like the above method, but is only one page. I'm pretty sure you can do this, but don't know the proper way to word it or what vocabulary to use when typing it in to google.
Some questions you may have:
Q:Why not use parameters like this:
web.url.com?pgid=some+page
A: I would like the url to be as clean as possible when it comes to the visitor typing the url. For example, this is much easier to remember:
web.url.com/about
than this:
web.url.com?p=about
Q: Wordpress??
A: We want our own stuff. Wordpress is great, but not for our project.
Q: JQuery?
A: PHP please.
Thank you in advance!
With PHP alone, I don't think it's possible. However, it's likely that your webserver is running Apache, which makes this task fairly straightforward by transforming your pretty URLs into ugly URLs (with query strings) that your PHP script can handle. Your visitors have no idea this is happening; they aren't redirected or anything.
I strongly recommend you take a look at this tutorial, and its followup. The second tutorial contains the information you need for this task (starting in this section), but I strongly recommend reading the first tutorial to gain a deeper understanding of what you're doing.
Essentially, those tutorials will teach you how to specify (ugly, scary-looking) URL-rewriting rules in a file called .htaccess. These rules will transform (or "rewrite") your pretty URLs into less pretty ones that your PHP script can handle.
For example, yoursite.com/about would actually be accessing yoursite.com/index.php?page=about, or something along those lines.
For some sample code, here's a snippet 95% copied and pasted from this tutorial:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
As that link explains, it will forward all requests to index.php, unless an actual file or directory is being requested.
Use a RewriteRule based .htaccess. Then you can have all non-existing files redirected (internally in Apache) to a general index.php with the requested path as a query string ?p=about. The redirecting is handled internally, so http://example.com/about is the external URL to that page.
You can have a switch statement checking $_GET values and output the page based on the provided parameter. Also, you will have to add some mod_rewrite rules to route those requests.
Use PHP URL rewrite. PHP will enteprate part of your URL as query string

Categories