user1800951
user1800951

Reputation: 1

.htaccess RewriteRule for URL Shortener

I am trying to build a very basic URL shortening website. I used almost all of basixnick's coding in this tutorial (https://www.youtube.com/watch?v=ZnthmFQKlVY all 3 parts) but I'm having an issue.

When you enter a URL into the shortening inbox, for example www.google.com, you will get the corresponding shortened code. Then when you copy and paste the URL, let's say www.mysite.com/xyz123, it will redirect you to www.mysite.com/www.google.com instead of simply www.google.com.

.htaccess looks like this. Is there an issue with the RewriteRule?

<Files .htaccess>
order allow,deny
</Files>

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^(\w+)$ ./load.php?code=$1

EDIT to question:

Here is my load.php file:

<?php
$code = $_GET['code'];

require("./connect.php");

$query = mysql_query("SELECT * FROM items WHERE code='$code'");
$numrows = mysql_num_rows($query);

if ($numrows == 1) {
    $row = mysql_fetch_assoc($query);
    $url = $row['url'];

    header("Location: $url");
}
else
    echo "No shortened url was found.";

mysql_close();

?>

When I remove the 'header(...)' code, and replace it with 'echo "$url";' the long url will be echoed just fine. So everything up to that point works fine. Maybe it's the 'header(...)' line. What do you think?

Upvotes: 0

Views: 2403

Answers (1)

Jon Lin
Jon Lin

Reputation: 143926

Something's wrong with load.php, there's nothing wrong with the rewrite rule. It looks like the redirect code is redirecting to /www.google.com instead of www.google.com.


EDIT:

If the $url variable is literally www.google.com, then this is the problem. The browser is going to assume that www.google.com is a relative URI, and append it to the URL path that it used to make the request, http://www.mysite.com/www.google.com.

You either need to make it so the URL that you shorten include a protocol (e.g. http:// or https://), or you make the protocol one or the other:

header("Location: http://$url");

Upvotes: 1

Related Questions