Помогите с перезаписью URL используя .htaccess - PullRequest
1 голос
/ 15 октября 2010

У меня есть html статические файлы на моем сервере. Я хочу, чтобы правила доступа были -

  1. Если пользователь посещает http://example.com/test/, он должен получить содержимое файла http://example.com/test.html
  2. Если пользователь посещает http://example.com/test (без завершающего слеша), он перенаправляется на http://example.com/test/ (который запускает правило 1 и получает ему содержимое файла test.html)
  3. Правила 1 и 2 должны запускаться, только если файл test.html существует.

Пока у меня есть -

Options All -Indexes -Multiviews
# Do not return details of server
ServerSignature Off

<IfModule mod_rewrite.c>
DirectorySlash Off
RewriteEngine On
RewriteBase /

# If it's a request to index.html
RewriteCond %{THE_REQUEST} \ /(.+/)?index\.html(\?.*)?\  [NC]
# Remove it.
RewriteRule ^(.+/)?index\.html$ /%1 [R=301,L]

# Add missing trailing slashes to directories if a matching .html does not exist.
RewriteCond %{SCRIPT_FILENAME}/ -d
RewriteCond %{SCRIPT_FILENAME}.html !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]

# If it's a request from a browser, not an internal request by Apache/mod_rewrite.
RewriteCond %{ENV:REDIRECT_STATUS} ^$
# And the request has a HTML extension. Redirect to remove it.
RewriteRule ^(.+)\.html$ /$1 [R=301,L]

# If the request exists with a .html extension.
RewriteCond %{SCRIPT_FILENAME}.html -f
RewriteRule ^(.*)/?$ $1.html [QSA,L]
</IfModule>

Хотя он работает для http://example.com/test,, он не работает для http://example.com/test/ (внутренняя ошибка 500)

Разве вторая последняя строка не должна заботиться о конечных слешах?

[Update] Если я использую предложения Gumbo (следует .htaccess), я получаю 404 для http://example.com/test и http://example.com/test/ (с косой чертой)

Options All -Indexes -Multiviews
# Do not return details of server
ServerSignature Off

ErrorDocument 404 /404.html

# Hide .htaccess 
<Files ~ "^\.ht">
Order allow,deny
Deny from all
</Files>

<IfModule mod_rewrite.c>
DirectorySlash On
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301]
RewriteRule ^([^/]+)/$ $1.html [L]

</IfModule>

[Обновление 2] Я сдался. Приведенный ниже код работает, но вместо того, чтобы принудительно завершать все с / (http://example.com/test/),, он удаляет косую черту (http://example.com/test). С другой стороны, он гарантирует, что на контент указывает только один URL, сохраняя SEO. Я собираюсь жить с этим сейчас.

Options All -Indexes -Multiviews
# Do not return details of server
ServerSignature Off

ErrorDocument 404 /404.html

# Hide .htaccess 
<Files ~ "^\.ht">
Order allow,deny
Deny from all
</Files>

<IfModule mod_rewrite.c>
DirectorySlash On
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

# If the request exists with a .html extension.
RewriteCond %{SCRIPT_FILENAME}.html -f
# And there is no trailing slash, rewrite to add the .html extesion.
RewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L]


</IfModule>

1 Ответ

2 голосов
/ 15 октября 2010

Попробуйте эти правила:

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301]
RewriteRule ^([^/]+)/$ $1.html [L]
...