drq1257 2012-09-14 10:00 采纳率: 0%
浏览 31
已采纳

使用mod_rewrite模拟Facebook样式的URL

What I want the address bar to show:

http://facebook.com/user

http://facebook.com/user/ -> http://facebook.com/user

http://facebook.com/user/photos -> http://facebook.com/user/photos

My rewrite rules:

RewriteEngine On
RewriteRule ^(.+)/$ $1 [NC]
RewriteRule ^([A-Za-z0-9_-]+)/?([A-Za-z0-9_-]*)$ user.php?id=$1&second=$2 [NC,L]

What happens:

1). http://domain.com/user (working well)

2). http://domain.com/user/ (keeps the / in the address bar and destroys css/js/img paths)

3). http://domain.com/user/photos (same result as 2, correct except the paths)

If I use <base href="..."> to force the paths the page displays correctly. But I want to solve my problem without it.

How can I remove the trailing slash in the address bar? The rewriting seem to be working like intended.

  • 写回答

2条回答 默认 最新

  • doubi5127 2012-09-14 10:07
    关注

    When you are going to use Friendly URLs, you must use absolute paths for your resources.

    Initial Declaration

    You might have declared index.php with this way:

    <link rel="stylesheet" href="stylesheets/styles.css" />
    <img src="assets/user.png" />
    <script type="text/javascript" src="scripts/home.js"></script>
    

    Proposed Way using / for Absolute Paths

    But it has to be translated this way:

    <link rel="stylesheet" href="/stylesheets/styles.css" />
    <img src="/assets/user.png" />
    <script type="text/javascript" src="/scripts/home.js"></script>
    

    Notice the / in the front to make them as Absolute URLs.

    Using <base href="/" />

    If this is going to be a tedious task for you, you can use this tag:

    <base href="/" />
    

    This will make your Relative URLs to relate with the Root.

    Using a $baseurl variable

    Another better way is to prepend with a $baseurl variable.

    <link rel="stylesheet" href="<?php echo $baseurl; ?>/stylesheets/styles.css" />
    <img src="<?php echo $baseurl; ?>/assets/user.png" />
    <script type="text/javascript" src="<?php echo $baseurl; ?>/scripts/home.js"></script>
    

    This way, you can even change the $baseurl value if you are hosting in a folder and not in the root!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常