开发者

htaccess - removal of extension - allow or force trailing slashes without breaking relative links

and thanks in advance for any help!

What I'm trying to achieve is this: I would like to remove the file extension from file names using htaccess - which is what I've done. However, when a user points their browser to a file without an extension and adds a trailing slash I get a page not found error. I found some code which corrected this, however, when I implemented the code, it broke my relative links to CSS and jQuery located in the head.

I really would rather like to keep relative links to all my files, but would also like to allow trailing slashes for individual files.

Is this possible?

My site is here: http://www.getagig.info

And my current htaccess code (which only removes extensions is below).

RewriteEngine on

RewriteCond %{REQUEST_FILENAME开发者_开发技巧} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php


Perhaps try:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ $1.php

Edit: I understand from your comment below what your issue is, but I've taken a look at your site, and I'm a little confused why you're trying to do it this way.

From what I understand, all you really want is for yourwebsite.com/filename or yourwebsite.com/filename/ to use filename.php, in which case you're better off using an .htaccess rule like the following:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ $1.php

This should still allow your CSS and JS files to load, as well as any file or directory that physically exists on your server. If you do not want people to physically call "filename.php", then you can set-up a separate rule for that.


I don't think it's possible to test if the file exists in RewriteCond if you have / appended to your url.

Only solution I can think of here would be using htaccess to redirect to some php file which will sort things out:

.htaccess:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !\.php$
RewriteRule ^(.*?)/?$ route.php?url=$1

.php file

<?php

$url = $_GET['url'];

if (strpos($url, '..') !== false || strpos($url, '/') !== false) {
  echo "No relative urls!";

} else if (file_exists($url)) {
  // do what you want - require or redirect to the requested file

} else {
  // requested file does not exist
}


Adding the line:

<BASE href="http://www.sitename.com/">

to my page inside the <head> tag works great for me. It can be coded even a PHP function to automatize this so you don't have to bother with copy/paste on other occasions.

Update:

<?php
$BaseDir = 'http://'.$_SERVER['SERVER_NAME'].substr($_SERVER["SCRIPT_NAME"], 0, strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
?>

<head>
...
<BASE href="<?php echo $BaseDir; ?>">
...
</head>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜