Drop trailing slash in apache for directory

I have the following url www.example.com/advice/ now notice the trailing slash at the end of the url? I would like that to be removed to be something like www.example.com/advice. Now when I enter that URL in the browser I get redirected to the with trailing slash, even with curl for example. Now I know the trailing slash is getting added because advice is an actual directory.

[steve@dev dev.www.example.com]$ curl -I  https://dev.www.example.com/advice -k
  HTTP/1.1 301 Moved Permanently
  Date: Fri, 25 Nov 2016 08:20:11 GMT
  Server: Apache/2.4.6 (CentOS)
  Location: https://dev.www.example.com/advice/
  Cache-Control: max-age=0
  Expires: Fri, 25 Nov 2016 08:20:11 GMT
  Connection: close
  Content-Type: text/html; charset=iso-8859-1

[steve@dev dev.www.example.com]$ curl -I https://dev.www.example.com/advice/ -k
HTTP/1.1 200 OK
Date: Fri, 25 Nov 2016 08:21:19 GMT
Server: Apache/2.4.6 (CentOS)
X-Powered-By: PHP/5.6.27
Set-Cookie: flarum_session=mfbou2hcbvcobhncnaqlvl9bm7; Path=/; HttpOnly
X-CSRF-Token: WV69M1oi8POqOcXi6MvwKhbJQ72Tmo2WpFn3oxwq
Content-Length: 10339
Cache-Control: max-age=0
Expires: Fri, 25 Nov 2016 08:21:19 GMT
Vary: Accept-Encoding
Access-Control-Allow-Origin: *.example.com
Connection: close
Content-Type: text/html; charset=UTF-8

What I tried so far


Inside of the .htacess I tried:

DirectorySlash Off

Which resulted into a 403 without the slash

[steve@dev dev.www.example.com]$ curl -I https://dev.www.example.com/advice -k
  HTTP/1.1 403 Forbidden
  Date: Fri, 25 Nov 2016 08:53:15 GMT
  Server: Apache/2.4.6 (CentOS)
  Connection: close
  Content-Type: text/html; charset=iso-8859-1

I also added the following rewrite rule but nothing changed

RewriteRule ^.*(advice)\/$ $1 [L,R=301]

More information


Now advice is where I have a forum platform installed, in the same directory I have a CMS installed, something like below

├── advice
│   ├── admin.php
│   ├── api.php
│   ├── assets
│   ├── composer.json
│   ├── composer.lock
│   ├── config.php
│   ├── CONTRIBUTING.md
│   ├── index.php <-- Forum entry point
│   ├── LICENSE
│   ├── Procfile
│   ├── readme.md
│   ├── scripts
│   ├── storage
│   ├── Vagrantfile
│   └── vendor
├── assets
├── cms
├── codeception.yml
├── commands
├── composer.json
├── composer.lock
├── crontask
├── dropzone
├── email-helpers
├── favicon.ico
├── framework
├── gridfield-bulk-editing-tools
├── gridfieldextensions
├── index.php <-- CMS Entry point
├── kickassets
├── liveseo
├── minify
├── README.md
├── reports
├── setup.php
├── shortcodable
├── silverstripe-cache
├── siteconfig
├── _ss_environment.php
├── tests
├── themes
├── trait-loader
├── vendor
└── web.config

Apache version Apache/2.4.6 (CentOS)

You can find the advice .htaccess here and the one in the cms here

If it helps the CMS is silverstripe and forum is flarum

1
задан 25 November 2016 в 11:11
1 ответ

Если вы удалите косую черту в каталоге и по-прежнему ожидаете, что документ индекса каталога (в этом каталоге) будет возвращен, вам необходимо вручную "исправить" URL-адрес, внутренне переписав его на индексировать документ. (В основном вам нужно повторить то, что вы отменили, отключив DirectorySlash .)

Попробуйте сделать что-нибудь вроде следующего перед другими директивами mod_rewrite в корне .htaccess файл:

DirectorySlash Off

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_FILENAME}/index.php -f
RewriteRule (.*) $1/index.php [L]

Для всех запросов к физическим каталогам, которые не заканчиваются косой чертой, где в этом каталоге существует index.php , затем внутренне перепишите в index.php .

В качестве альтернативы, вы можете просто добавить завершающую косую черту (путем внутренней перезаписи), а затем разрешить mod_dir выдать подзапрос к DirectoryIndex . Например:

RewriteRule (.*) $1/ [L]

Предполагая, что у вас есть набор DirectoryIndex (который, вероятно, у вас есть, если он работал ранее), тогда mod_dir внутренне перепишет запрос (строго подзапрос) из / advice / С на /advice/index.php . Однако теперь это двухэтапный процесс, поэтому вы можете сделать это все за один с помощью mod_rewrite (если у вас нет документов с различными индексами каталогов).


Вышеупомянутое является общим случаем для всех каталогов.Вы могли бы быть более конкретными и проверить только соответствующий каталог / URL:

RewriteRule ^advice$ advice/index.php [L]

Если запрос предназначен для / advice , то внутренне перепишите его на /advice/index.php - это не проверяет, является ли это каталогом, это просто предполагается.

1
ответ дан 3 December 2019 в 23:37

Теги

Похожие вопросы