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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改