.htaccess mod_rewrite URL query - php

I was hoping someone could help me out. I'm building a CRM application and need help modifying the .htaccess file to clean up the URLs. I've read every post regarding .htaccess and mod_rewrite and I've even tried using http://www.generateit.net/mod-rewrite/ to obtain the results with no success. Here is what I am attempting to do.
Let's call the base URL www.domain.com
We are using php with a mysql back-end and some jQuery and javascript
In that "root" folder is my .htaccess file. I'm not sure if I need a .htaccess file in each subdirectory or if one in the root is enough.
We have several actual directories of files including "crm", "sales", "finance", etc.
First off we want to strip off all the ".php" extensions which I am able to do myself thanks to these posts. However, the querying of the company and contact IDs are where I am stuck.
Right now if I load www.domain.com/crm/companies.php it displays all the companies in a list.
If I click on one of the companies it uses javascript to call a "goto_company(x)" jQuery script that writes a form and submit that form based on the ID (x) of the company. This works fine and keeps the links clean as all the end user sees is www.domain.com/crm/company.php. However you can't navigate directly to a company.
So we added a few lines in PHP to see if the POST is null and try a GET instead allowing us to do www.domain.com/crm/company.php?companyID=40 which displays company #40 out of the database.
I need to rewrite this link, and all other associated links to www.domain.com/crm/company/40
I've tried everything and nothing seems to work. Keep in mind that I need to do this for "contacts" and also on the sales portion of the app will need to do something for "deals".
To summarize here's what I am looking to do:
Change www.domain.com/crm/dash.php to www.domain.com/crm/dash
Change www.domain.com/crm/company.php?companyID=40 to www.domain.com/crm/company/40
Change www.domain.com/crm/contact.php?contactID=27 to www.domain.com/crm/contact/27
Change www.domain.com/sales/dash.php to www.domain.com/sales/dash
Change www.domain.com/sales/deal.php?dealID=6 to www.domain.com/sales/deal/6
(40, 27, and 6 are just arbitrary numbers as examples)
Just for reference, when I used the generateit.net/mod-rewrite site using www.domain.com/crm/company.php?companyID=40 as an example, here is what it told me to put in my .htaccess file:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^crm/company/([^/]*)$ /crm/company.php?companyID=$1 [L]
Needless to say that didn't work.
OK here is an updated based on the help received from Gohn67 below
It is working with the exception of a small bug I can't seem to figure out. I have created the .htaccess file in the "crm" directory. Here is the code:
RewriteEngine On
RewriteRule ^test/([\d]+)$ /crm/company.php?companyID=$1 [L]
This rewrites www.domain.com/test/40 to www.domain.com/crm/company.php?companyID=40 so it's very close to what I need.
The bug is that I cannot replace "test" with the word "company" in my RewriteRule. I do not know why. I can put anything but the word "company" in there; even the names of other PHP files in the "crm" directory such as "contact" or "add-contact". As a further test I actually renamed company.php to test.php and changed the RewriteRule to:
RewriteRule ^company/([\d]+)$ /crm/test.php?companyID=$1 [L]
which worked.

Yeah, the generated rewrite looks kind of strange there. I'm not sure what it is trying to match here ([^/]*).
Here is an example that may work for you. I tested these on my system.
RewriteEngine On
RewriteRule ^crm/dash/?$ /crm/dash.php [L]
RewriteRule ^crm/company/([\d]+)/?$ /crm/company.php?companyID=$1 [L]
RewriteRule ^crm/contact/([\d]+)/?$ /crm/contact.php?contactID=$1 [L]
This is only a few of your routes as an example. I admit that they could be more robust though, because doing this way will lead to a lot of rewrite rules, some of which you could elminate with better regex patterns. But hopefully this gets you started.
Here are some updated rewrite rules taking into consideration a subdirectory. It also fixes a a mistake from above:
RewriteEngine On
RewriteBase /crm
RewriteRule ^dash/?$ dash.php [L]
RewriteRule ^company/([\d]+)/?$ company.php?companyID=$1 [L]
RewriteRule ^contact/([\d]+)/?$ contact.php?contactID=$1 [L]

Related

Changing link apperance with .htaccess

I'm trying to do simple trick with .htaccess file, but with without success.
Generally I have PHP script that makes dynamically generated signatures and link looks like this:
example.com/signature/generate.php?name=%SomeUserName%
where %SomeUserName% is simply username e.g. Patison
and I'm trying to get:
example.com/signature/%SomeUserName% or (if necessary)
example.com/signature/generate/%SomeUserName%
Last code that I'm tried with no success:
RewriteEngine On
RewriteRule ^/signature/generate.php?name=(*) /signature/$1 [L,NC]
.htaccess is hard to understand for me.
So I have one more question. When someone use this link on another site he will render an image or it will work only on mine?
This is the sort of approach you need:
RewriteEngine on
RewriteRule ^signature/([^/\.]+)?$ signature/generate.php?name=$1 [L,NC,QSA]
So anybody going to signature/levi will see signature/generate.php?name=levi

URL Routing using RewriteRule

I am trying to create my own PHP MVC framework for learning purpose. I have the following directory structure:
localhost/mvc:
.htaccess
index.php
application
controller
model
view
config/
routes.php
error/
error.php
Inside application/config/routes.php I have the following code:
$route['default_controller'] = "MyController";
Now what I am trying to achieve is when any user visits my root directory using browser I want to get the value of $route['default_controller'] from route.php file and load the php class inside the folder controller that matches with the value .
And also if any user tries to visit my application using an url like this: localhost/mvc/cars, I want to search the class name cars inside my controller folder and load it. In case there is no class called cars then I want to take the user to error/error.php
I guess to achieve the above targets I have to work with the .htaccess file in the root directory. Could you please tell me what to code there? If there is any other way to achieve this please suggest me.
I have tried to use the .htaccess codes from here, but its not working for me
It all sounds well and good from a buzzword standpoint, but to me this is all a little confusing because I see PHP's model as an MVC model already. It's providing the API for you to program with and deliver your content to your web server Apache and your database (something like MySQL). It translates the code(model) for you into HTML(view) ... provided that's what you intend, and you're supplying code as the user input (control). Getting too wrapped up in the terminologies gets a little distracting and can lead to chaos when you bring someone in to collaborate who isn't familiar with your conventions. (This should probably never be used in a production environment for a paying gig.)
I can tell you that on the page that you referenced they guy's .htaccess file needs a little work. The [L] flag tells mod_rewrite that this is the last command to process when the rule returns true. So you would either need to do this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
Or the following... but he was using a passthru flag which means that he is implying there are other things that could be processed prior to the last rule (eg. might be rewrite_base or alias), but that's not actually the case with his .htaccess file since it's a little bare. So this code would work similar to the code above but not exactly the same. They can't be used together though, and really there would be no need to:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?url=$1
</IfModule>
The difference is the in the way it's processed. On the first .htaccess example you're passing any file to index.php regardless of whether it exists or not. You can [accidentally] rewrite a path that has a real file so that the real file is never accessed using this method. An example might be you have a file called site.css that can't be accessed because it's being redirected back to index.php.
On the second ruleset he's at least checking to see if the server doesn't have a file or a directory by the name being requested, then they're forwarding it to index.php as a $_GET variable (which seems a little pointless).
The way I typically write these (since I know mod_rewrite is already loaded in the config) is to to this:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain.com
RewriteRule (.*) http://www.mydomain.com/$1 [R=301,L]
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule .* index.php
In my PHP code I pull the $_SERVER['REQUEST_URI'] and match it against a list of URIs from the database. If there's a match then I know it's a real page (or at least a record existed at some point in time). If there's not a match, then I explode the request_uri and force it through the database using a FULLTEXT search to see what potentially might match on the site.
Note: if you blindly trust the request_uri and query the database directly without cleaning it you run the risk of SQL injection. You do not want to be pwnd.
<?php
$intended_path = $_SERVER['REQUEST_URI'];
if(in_array($intended_path,$uris_from_database)){
//show the page.
} else {
$search_phrase = preg_replace('!/!',' ',$intended_path);
$search_phrase = mysqli_real_escape_string($search_phrase);
$sql = "SELECT * FROM pages WHERE MATCH (title,content) AGAINST ('$search_phrase');"
}
Sorry if this sounds a bit pedantic, but I've had experience managing a couple of million dollar (scratch) website builds that have had their hurdles with people not sticking to a standard convention (or at least the agreed upon team consensus).

mod_rewrite url

I noticed on youtube their url does not have a file extension and querystring. I've been trying to emulate something similar but found I had to either include the file extension or a trailing slash.
members.php?agefrom=20&ageto=40&city=london (works)
members/?agefrom=20&ageto=40&city=london (works)
members?agefrom=20&ageto=40&city=london (doesnt work)
So I was just wondering how can I get the third case to work? i've tried a few things in the htaccess file.
RewriteRule ^members$ index.php?page=members&%{QUERY_STRING} [QSA,L]
I have tried the above but to no avail.
Any help would be appreciated.
The RewriteRule that you posted is correct for members.php? and for members? It should not work with members/
You must have additional RewriteRules before this one that are getting applied first and are affecting this rule.
However, here is a rule that should still work for you:
RewriteRule ^members/?$ index.php?page=members&%{QUERY_STRING} [QSA,L]
The /? is saying to match if the slash exists or if it doesn't exist.
Have you tried to remove the $ on the end?
RewriteRule ^members/?$ index.php?page=members&%{QUERY_STRING} [QSA,L]
This did work in the end, all I had to do was move it nearer the top of the htaccess file. I had the following line which I guess was being read instead.
....
RewriteCond %{REQUEST_URI} ^/members$ [OR]
....
I am changing my approach to SEO URL's because I was trying to find articles on how the googlebot actually crawls forms and how it prefers the GET method. I was using jquery to alter my action parameter to write the following URL:
/members/london/18-to-25
I dont know how much google likes jquery and whether it would scan javascript code. I am assuimg it just follows the HTML code and having done some research I have changed my form to use the GET method and so the bot can crawl my form without complaining so now my URL looks like this:
/members?location=london&agefrom=18&ageto=40
I am on the right track to assume this? or should I just stick with jquery to rewrite the action parameter for an seo friendly URL?

.htaccess mod_rewrite redirect issue

I have currently hit a bit of an issue with redirecting users with .htaccess and was wondering if anyone could help me.
1. Background:
I currently have a rather long domain name for the sake of this question lets refer to it as mylongdomainname.com now on this domain I have a subdomain that I use to host files, pictures etc to show friends or share with people this is files.mylongdomainname.com
now obviously the URL can get quite long as I have different directories and files. so to help reduce a bit of space I purchased another short domain, lets refer to this as small.me now what I want to do is use .htaccess and a simple PHP file to redirect small.me to files.mylongdomainname.com and pass on a file reference.
Example:
small.me/pictures/example.jpg should redirect to files.mylongdomainname.com/pictures/example.jpg
2. The problem
Basically I am unsure on the exact rewrite rule I would need to acomplish this. obviously I need a rule that will allow anything after small.me/ to be sent with the GET method to the index file which would then redirect the user accordingly. So that means that the rewrite rule will have to allow all letters, numbers and valid file name symbols to be used. I'm sure it's simple but after looking at a few tutorials and mod_rewrite help sites I still have no idea how to accomplish this.
3. The Code
.htaccess
RewriteEngine on
RewriteRule ^$ index.php?file_location=$1 [L]
obviously wrong
index.php
<?php
//Get the requested files location.
$file_location = $_GET['file_location'];
//Redirect the user to the file.
header('refresh:2; url=http://files.mylongdomainname.com/' . $file_location);
?>
4. Notes
I am aware I could just use a URL shortener, but because I am awkward I would rather it just went through my own domain, so please don't comment or answer telling me to use a shortener or to use a service like dropbox.
So can anybody help me by providing the right rule? Any help is much appreciated.
In .htaccess you can simply use:
RewriteRule ^(.*)$ http://small.me/?$1 [L]
No need for the PHP file if that's all you're trying to do.
Assuming you want this:
Picture to be shared: http://files.mylongdomainname.com/pictures/me/troll.jpg
Desired URL: http://small.me/pictures/me/troll.jpg
Remove the PHP file, just Place this in small.me's htaccess:
RewriteRule ^\/?(.*)$ http://files.mylongdomainname.com/$1 [NC,L]
The following in your .htaccess file should be all you need (no PHP file needed):
RewriteRule ^(.*) http://files.mylongdomainname.com/$1 [RL]
For more information and examples see the mod_rewrite documentation

Pretty URLs from DB

I am working on creating page links from DB like the following example.
Current page:
www.example.com/page.php?pid=7
In the DB it is saved as title "contact-us" under category "Company Info"
I want it to be like:
www.example.com/company-info/contact-us.html
I have tried different solution and answers but did not got any luck. I am not sure, where will be the PHP part and which rules to write for .htaccess files.
In apache (or .hataccess) do something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /proxy.php?_url=$1 [QSA,L]
So in a nutshell, if the resource being requested doens't exist, redirect it to a proxy.php file. From there $_REQUEST['_url'] will be the url the user was requesting.
Then create proxy.php in your home directory and add whatever logic you'd like to load the correct content.
If you use this from .htaccess, then you may need to add RewriteBase / to your config.
If you want to find this page by url, you will probably do this through php and .htaccess. Make a .htaccess that calls page.php for each and every request. You don't need the pid=7, because, well, how should the .htaccess know it is 7, right? :)
In page.php, you take the original url and split it on the slashes, so you get the category (company-info) and the page itself (contact-us.html). Then, you can look these up in the database. This is in a nutshell how many software works, including Wikipedia (MediaWiki) and CodeIgnitor.
Mind that 'company-info' isn't the same as 'Company Info'. You'll have to specify the url-version in the database to be able to use it for look-up.

Categories