htaccess的重写规则 - 没有扩展名和斜杠斜杠、扩展名、重写、规则

2023-09-02 20:33:01 作者:有得必有失,有失必有得/

我不熟悉的.htaccess文件,所以原谅我,如果我的问题是有点荒唐。

I am not familiar with .htaccess file so excuse me if my question is a little absurd.

当我请求

localhost/mydomain/blog.php

我想有这种形式的网址:

I want to have a url of this form:

localhost/mydomain/blog/

我的网站目录看起来像这样:

My website directory looks like that:

.htaccess文件包含以下内容:

The .htaccess file includes the following:

删除扩展名为.php

Remove .php extension

<IfModule mod_rewrite.c>        
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]
</IfModule>

通过此链接

<a href="blog">Blog</a>

网址为:

localhost/createforweb_1.1/blog

不过,我想增加斜线,所以如果我的.htaccess中加入这些行:

But I want to add a trailing slash, so if I add these lines in htaccess:

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://localhost/createforweb_1.1/$1/ [L,R=301]

我得到这个错误:

I get this error:

The requested URL /blog/.php was not found on this server.

我敢肯定,是很简单的,但我有在.htaccess重写的一点经验!

I'm sure is very simple but I have a little experience in .htaccess rewrite!

<IfModule mod_rewrite.c>
 Options +FollowSymlinks
# Options +SymLinksIfOwnerMatch
 RewriteEngine On
# RewriteBase /
</IfModule>

Options -MultiViews

## Adding a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

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

的替代解决方案

我刚刚创建了一个文件夹中的每一页,感动里面的文件,并给他们改名到index.php。新的目录树的样子说:

ALTERNATIVE SOLUTION

I just created a folder for every page, moved the files inside and renamed them into index.php. The new directory tree looks like that:

现在我要求博客目录和博客/ index.php文件加载。 URL成为createforweb.gr/blog /

Now I request blog folder and blog/index.php is loading. URL becomes createforweb.gr/blog/

这是一个可以接受的解决方案,或将在未来产生问题?

Is this an acceptable solution, or it will create problems in the future?

推荐答案

将这个code在的.htaccess DOCUMENT_ROOT 目录:

Put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## Adding a trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

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