mod_rewrite删除.php但仍然提供.php文件?

Nic*_*ard 2 php apache mod-rewrite

我只想用mod_rewrite做一个简单的事情.我有一个使用.php文件的站点,我想重写那些更干净的URL,并删除.php.因此,文件将是www.mysite.com/contact等.

这确实按照我想要的方式工作,但我原本以为它仍会提供我的contact.php文件,但只是向用户显示他们在/ contact而不是contact.php.但是,它正在寻找一个名为联系人的文件,它不存在.

那么,我需要做什么,仍然使用我的contact.php文件,但是将用户的URL重写为/ contact?

这是我正在使用的:

SetEnv APPLICATION_ENV development
RewriteEngine on
RewriteBase /

# Always use www.
RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]
RewriteRule ^(.*)$ http://www.mysite.com/$1 [L,R=301]

# Change urlpath.php to urlpath
RewriteCond %{HTTP_HOST} ^www\.mysite\.com$ [NC]
RewriteRule ^(.*)\.php$ http://www.mysite.com/$1 [L,R=301]
Run Code Online (Sandbox Code Playgroud)

Nei*_*sby 7

对于此解决方案,我遵循以下规则:

  1. 如果用户尝试加载/something.php,则应将其外部重定向到/something.
  2. 如果用户尝试加载/something,则应将其内部重定向到/something.php.
  3. 如果用户将任何查询字符串参数传递给URL,则应通过重定向保留这些参数.
  4. 如果用户尝试加载文件系统中真正存在的其他文件(样式表,图像等),则应按原样加载.

这是mod_rewrite魔法的最终设置:

RewriteEngine on
RewriteBase /

## Always use www.
RewriteCond %{HTTP_HOST} ^mysite\.com$ [NC]
RewriteRule ^(.*)$ http://www.mysite.com/$1 [L,R=301]

# Change urlpath.php to urlpath
## Only perform this rule if we're on the expected domain
RewriteCond %{HTTP_HOST} ^www\.mysite\.com$ [NC]
## Don't perform this rule if we've already been redirected internally
RewriteCond %{QUERY_STRING} !internal=1 [NC]
## Redirect the user externally to the non PHP URL
RewriteRule ^(.*)\.php$ $1 [L,R=301]

# if the user requests /something we need to serve the php version if it exists

## Only perform this rule if we're on the expected domain
RewriteCond %{HTTP_HOST} ^www\.mysite\.com$ [NC]
## Perform this rule only if a file with this name does not exist
RewriteCond %{REQUEST_FILENAME} !-f
## Perform this rule if the requested file doesn't end with '.php'
RewriteCond %{REQUEST_FILENAME} !\.php$ [NC]
## Only perform this rule if we're not requesting the index page
RewriteCond %{REQUEST_URI} !^/$
## Finally, rewrite the URL internally, passing through the user's query string
## using the [qsa] flag along with an 'internal=1' identifier so that our first
## RewriteRule knows we've already redirected once.
RewriteRule ^(.*)$ $1.php?internal=1 [L, QSA]
Run Code Online (Sandbox Code Playgroud)