Toby
Toby

Reputation: 717

How to change URL's to friendly URL in PHP (Htaccess)

I want to change:

example.com/movie.php?id=550

to

example.com/movie/550

This is my code in .htaccess file

ErrorDocument 404 http://example.com/error404.php

php_flag display_errors 1

RewriteEngine On

RewriteRule ^([a-zA-Z0-9]+)$ movie.php?id=$1

This is what the code does:

It opens the page example.com/movie.php?id=550

When I type:

example.com/550

And When I type:

example.com/movie/550

then it redirects me to this URL:

example.com/movie.php?id=550

Expected Result:

When I type: example.com/movie/550 it should open the content inside this page: example.com/movie.php?id=550 (no redirect)

And when I type example.com/550, it re-directs me to example.com/error404.php page

Upvotes: 0

Views: 111

Answers (1)

arkascha
arkascha

Reputation: 42905

There must be some other redirection rule intervening here. The rule above certainly will internally rewrite as in the first example, it is not responsible for a redirection as you describe in the second example. Probably some other, general rewriting rule implemented by the framework you use.

About the specific rule, I assume that is what you are looking for:

RewriteEngine On
RewriteRule ^/?movie/(\d+)/?$ /movie.php?id=$1

For that to work you obviously need the rewriting module to be active and you need to have the interpretation of dynamic configuration files enabled if you want to place the rule in one of those (see the AllowOverride directive). That would have to be located in your http hosts document root then.

Above rule will work in both, the http servers host configuration and likewise in dynamic configuration files.


And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only supported as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).

Upvotes: 1

Related Questions