user1661677
user1661677

Reputation: 1272

Rewrite PHP query string?

I've searched for other solutions to rewriting a URL using the .htaccess file at the root of my server, but the language is pretty confusing to me, and I can't seem to get it to work. How would I go about changing:

http://domain.com/share.php?media=059ogbuq70

to:

http://domain.com/059ogbuq70

I found code similar to this, and tried it, but it didn't seem to work:

RewriteEngine on
RewriteCond %{QUERY_STRING} ^media=([0-9]+)$
RewriteRule ^$ share.php?media=$1 [QSA,L]

My PHP:

<?php
$media_id = $_GET['media'];
$url = file_get_contents("https://api.wistia.com/v1/medias/" . $media_id . ".json?api_password=my_key");
$json = json_decode($url, true);
$name = $json[name];
$origimg = $json['thumbnail'][url];
list($image, $size) = explode('?', $origimg);
$video = $json['assets'][5][url];
?>

I then echo the variables where I need them on my page.

Thank you!

Upvotes: 1

Views: 2940

Answers (2)

Panama Jack
Panama Jack

Reputation: 24448

You need two rules for what you are trying to do. You can place this in the file called .htaccess

RewriteEngine on

#redirect all old URLs to the new rewritten URL
RewriteCond %{THE_REQUEST} ^GET\ /+share\.php\?media=([^&\ ]+)
RewriteRule ^ /%1? [R=302,L]

#rewrite folder path internally to share.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ share.php?media=$1 [QSA,L]

Upvotes: 1

showdev
showdev

Reputation: 29168

To internally rewrite "pretty" URLs so that query strings are passed to PHP, I recommend the following .htaccess file:

RewriteEngine on
RewriteRule ^([^/]+)/?$ share.php?media=$1 [L]

The regex matches:
One or more characters that are not a backslash, optionally followed by a backslash.

Everything but the optional trailing slash are captured in $1 and rewritten as the "media" query string variable.

For example:

http://domain.com/059ogbuq70/
rewrites internally to
http://domain.com/share.php?media=059ogbuq70

Which means that:

$_GET['media'] = 059ogbuq70


You might find this mod_rewrite cheat sheet helpful for building your regex.
Also, you can test your rewrites here.

Upvotes: 1

Related Questions