开发者

PHP: Best solution for links breaking in a mod_rewrite app

I'm using mod rewrite to redirect all requests targeting non-existent files/directories to index.php?url=*

This is surely the most common thing you do with mod_rewrite yet I have a problem:

Naturally, if the page url is "mydomain.com/blog/view/1", the browser will look for images, stylesheets and relative links in the "virtual" directory "mydomain.com/blog/view/".

Problem 1:

  • Is using the base tag the best solution? I see that none of the PHP frameworks out there use the base tag, though.

  • I'm currently having a regex replace all the relative links to point to the right path before output. Is that "okay"?

Problem 2:

It is possible that the server doesn't support mod_rewrite. However, all public files like images, stylesheets and the requests collector index.php are lo开发者_运维问答cated in the directory /myapp/public. Normally mod_rewrite points all request to /public so it seems as if public was actually the root directory too all users.

However if there is no mod_rewrite, I then have to point the users to /public from the root directory with a header() call. That means, however that all links are broken again because suddenly all images, etc. have to be called via /public/myimage.jpg

Additional info: When there is no mod_rewrite the above request would look like this: mydomain.com/public/index.php/blog/view/1

  • What would be the best solutions for both problems?

Edit/Additional question:

Is there a way to make /public/ the base dir using plain htaccess code?


Write the app in such a way that it doesn't need mod_rewrite to function (at the cost of having "ugly" urls). Progressively enhance it with mod_rewrite to achieve the desired result. This probably means that you'll need to store some base path config info in your app.


I don't understand these problems at all. Yes, this is surely the most common thing you do with mod_rewrite, yet with 2 conditions:

RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d

So, nothing hurt your existing images.

Why not to use just absolute path, e.g. /myapp/public/myimage.jpg, so, no virtual directory will hurt image path?


what about path info? You could use it without mod_rewrite

/index.php/path/to/another/file.jpg

<?php
echo $_SERVER["PATH_INFO"]; // outputs /path/to/another/file.jpg
?>

Anyways, if you want to know if mod_rewrite is supported by your server :

<?php
echo "mod_rewrite : ".(!empty($_SERVER["REDIRECT_URL"])?"supported":"not supported");
?>

Then you ll know if mod_rewrite is the solution or maybe path_info is more well suited for you, you could make support functions that could look for both too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜