如何让htaccess区分文件和ID

时间:2017-10-21 19:31:14

标签: .htaccess

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d # not an existing dir
RewriteCond %{REQUEST_FILENAME} !-f # not an existing file
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.php -f # and page.php exists

# redirect to the physical page
RewriteRule ^(.*)$ $1.php [L]

# otherwise, redirect to serve.php
RewriteRule ^ /serve.php [L]

RewriteRule ^(\w+)$ ./serve.php?id=$1

因此,在代码的第一部分中,我只需将http转换为https。我的目标是我可以在没有.php的情况下使用网址,但在我的旧代码中,我遇到的问题是,如果我这样做,它会被用作我的serve.php页面的ID。因此,如果使用https://example.com/contact,它就像https://example.com/serve.php?id=contact,但我希望它以https://example.com/contact.php的形式工作,但另一方面,我希望那些不是方向或文件的ID仍应作为ID工作。我的旧代码是......

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

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

    RewriteRule ^(\w+)$ ./serve.php?id=$1

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [NC,L]

1 个答案:

答案 0 :(得分:0)

您可以在站点根目录中使用这些规则.htaccess:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# skip rules below this for files and directories
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]


# rewrite to the physical php page
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

# otherwise, redirect to serve.php
RewriteRule ^/?$ serve.php [L]

RewriteRule ^(\w+)/?$ serve.php?id=$1 [L,QSA]