Home PHP - Using mod_rewrite in Apache
Reply: 1

PHP - Using mod_rewrite in Apache

user3352904
1#
user3352904 Published in 2017-11-11 16:16:44Z

I have the following URL:

http://example.com/pages/page.php?company_name=Name

What I want to achieve is to have a URL like this:

http://example.com/pages/Name

I have tried different rules but they don't work:

RewriteRule ^pages/([A-Za-z0-9-]+)/?$ /pages/page.php?company_name=$1 [NC] or

RewriteRule ^pages/([^/]*)\.php$ /pages/page.php?company_name=$1 [L]

It doesn't work. It gives me a "not found" page. How can I properly use mod_rewrite?

IncredibleHat
2#
IncredibleHat Reply to 2017-11-11 19:57:23Z

Try this out:

RewriteRule ^pages/([0-9a-zA-Z\-_]*)(/|)$ /pages/page.php?company_name=$1 [QSA,L]

This will care or not care if the url has a trailing slash:

http://example.com/pages/Name
http://example.com/pages/Name/

And will also include any extra agrs (QSA) if the page calls for it:

http://example.com/pages/Name/?more=stuff

That should work, if your apache has mod_rewrite and the php exists where you have shown.

UPDATE

If you have a different url that needs a different php, for example 'bluepages':

http://example.com/bluepages/Name

Then this would work for that:

RewriteRule ^bluepages/([0-9a-zA-Z\-_]*)(/|)$ /bluepages/somescript.php?some_var=$1 [QSA,L]

If you have multiple like this you wish to control, you can make multiple RewriteRules in your htaccess for each one. However if you just want to wildcard it, then this would do a blind catchall (and cause lots of error reports in your apache logs):

RewriteRule ^([0-9a-zA-Z]*)/([0-9a-zA-Z\-_]*)(/|)$ /$1/page.php?some_var=$2 [QSA,L]

You will either need to be specific, or just change everything. There are so many ways one can go with it, and it really depends on your intent.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.412134 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO