Question

I'm building a simple site that will only have a homepage and a contact page and wondered if I could use .htaccess to rewrite the urls for different companies.

So for example if I go to website.com/companyname-contact/ it will display that url in the browser bar but actually load a generic contact.php page, I can then use php to pull in the correct contact details for that specific companyname.

This would need to work for different company names (e.g. website.com/anothercompany-contact/) but only work for an array of approved company names.

I realise this may not be possible but I thought I'd ask because i spent about 4 hours this morning Googleing it with no real progress.

Thanks

Was it helpful?

Solution

Unless you want to manually list the approved company names in your .htaccess file (which looks UGLY) I'd suggest this:

RewriteEngine On 


  RewriteRule (.*)-contact$ /contact.php?company_name=$1 [L,QSA,NC]

and then in your contact.php

  • determine if valid company name - check db or whatever method you are using. (Make sure to escape the input)
  • if not valid you have a couple options:
    • redir to your default 404 page
    • issue an intelligent warning page (ie include suggestions for alternate spelling that is in the db) and set a 404 header. (better IMO)
    • if similar company name in the db possibly redirect to that with a note at the top of the page

OTHER TIPS

Yes you can. You need to enable the rewrite engine, and then you will be able to use regular expressions to accomplish what you're trying to do.

This is an example of what your htaccess could like:

RewriteEngine On
RewriteRule    ^contact/([A-Za-z0-9-]+)/?$    contact.php?company=$1    [NC,L]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top