doujing5937 2015-02-16 22:43
浏览 45
已采纳

尝试使用.htaccess缩短URL,但遇到配置错误

Brief intro: I'm attempting to set up a short URL system using a database and php. I've however came across a much shorter/quicker approach using a .htaccess file, regex, and a local config file. This tutorial however doesn't offer much support or explanation, and it's the first instance of URL re-writing I've seen.

Here's the code for the php script that gets the arguments passed into the page:

<?php

$links = parse_ini_file('links.ini');

if(isset($_GET['l']) && array_key_exists($_GET['l'], $links))
{
    header('Location: ' . $links[$_GET['l']]);
}
else
{
    header('HTTP/1.0 404 Not Found');
    echo 'Unknown link.';
}

?>

So in other words it checks to see if the argument passed is in the static config file (example here would be google: http://example.com/index.php?l=google), and if so, then of course re-directs them to the site. Configuration file contents:

google  = https://www.google.com/
fb      = https://www.facebook.com/

Fairly logical. Can understand how it works. My problem however comes with the .htaccess file as mentioned above. I've only dabbled with regex, and plan to learn more. However currently I'm not skilled enough to really understand the syntax required to write what is needing to be achieved. What needs to happen is for the user to basically type in www.example.com/url/google and for them to be re-directed to www.example.com/url/index.php?l=google - this is something I've been unable to get to work, and I just receive web server config errors. Config file for .htaccess:

RewriteEngine On

RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?l=$1 [L]

Can anyone advise on the cause of the issue? Sorry for the lack of understanding on the regex part. I'm trying to skill up on it. I'd just like to get the fix in place so I can continue on my project, as it's only a small part of it.

Thanks a lot.

  • 写回答

1条回答 默认 最新

  • douceng7070 2015-02-16 23:17
    关注

    This will redirect it:

    RewriteEngine On
    
    RewriteCond %{REQUEST_URI} ^/url/([a-z]+)$ [NC]
    RewriteRule ^ /url/index.php?l=%1 [R=301,L]
    
    RewriteCond $1 !^(index\.php)
    RewriteRule ^(.*)$ index.php?l=$1 [L]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?