1

I have a site with a video player, created with php. I have mangaged to clean up the URL from www.website.com/player.php?id=10 to www.website.com/player/10, where 10 is the id for a given video.

The code for the .htaccess file is like this:

RewriteEngine On
RewriteRule ^player/([0-9]+)$ player.php?id=$1

This works fine if I directly enter www.website.com/player/10, however, if someone tries to access the old links, they are not redirected. How can I do this in the .htaccess file?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
T. Nilsen
  • 11
  • 1
  • Rewrites doesn't redirect to the new URL. It simply takes a matched URL and internally calling the other URL. To have a better control over it, I would recommend that you look into using some router instead. – M. Eriksson Feb 05 '18 at 20:22
  • You can use `.htaccess` to set up another Redirect rule for the original `player.php` URL. [This Q&A may help.](https://stackoverflow.com/questions/1421068/htaccess-301-redirect-of-single-page) – Aken Roberts Feb 05 '18 at 20:26

1 Answers1

0

There's a difference between Redirect and Rewrite.

Redirecting issues an HTTP header to the client forcing them to request the new location. Rewriting is internal to the server and maps the requested location to a different one.

So, just redirect the "old" style to the "new" style and rewrite the "new" style:

# Match id in the query string and capture the id
RewriteCond %{QUERY_STRING}     ^id=(.*)$         [NC]
# Redirect the old to the new player/id
RewriteRule ^player.php$        player/%1         [NC,R=301,L]
# Rewrite the new to the old
RewriteRule ^player/([0-9]+)$   player.php?id=$1
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • Hmm.. I don't think you can access the get params like that in your first rewrite rule. – Chin Leung Feb 05 '18 at 20:33
  • @ChinLeung: You're probably right. Does that look better? – AbraCadaver Feb 05 '18 at 20:44
  • Your rule is going to loop as `player.php?id=$1` of your second Rule also matches the Rewrite pattern and RewriteCond of the first one. To prevent this loop ,you need to match against `%{THE_REQUEST}` variable instead of `%{QUERY_STRING}` – Amit Verma Feb 06 '18 at 12:43
  • @starkeen: You'll have to be more specific about what matches what, I don't see it. – AbraCadaver Feb 06 '18 at 14:18
  • See this similar post https://stackoverflow.com/questions/21578126/infinite-loop-while-using-modwrite-in-htaccess – Amit Verma Feb 06 '18 at 15:25