PHPackages                             josefglatz/htaccess-parser - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. josefglatz/htaccess-parser

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

josefglatz/htaccess-parser
==========================

A .htaccess parser and validator implemented in PHP

01PHP

Since Sep 12Pushed 2y agoCompare

[ Source](https://github.com/josefglatz/php-htaccess-parser)[ Packagist](https://packagist.org/packages/josefglatz/htaccess-parser)[ RSS](/packages/josefglatz-htaccess-parser/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

PHP Htaccess Parser [![SensioLabsInsight](https://camo.githubusercontent.com/78abcd0ed4a09e3eb900e88d912e880b25c12518f0c2ba55792682a3d53dabc0/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f38626431306532632d333364352d343830302d386431392d6539626532333632656565662f736d616c6c2e706e67)](https://insight.sensiolabs.com/projects/8bd10e2c-33d5-4800-8d19-e9be2362eeef)
==========================================================================================================================================================================================================================================================================================================================================================================================================

[](#php-htaccess-parser-)

[![Build Status](https://camo.githubusercontent.com/88b389e3daef862d26768502fa06ae18dba30fa9435833b9580eaaaab23e9503/68747470733a2f2f7472617669732d63692e6f72672f74697669652f7068702d68746163636573732d7061727365722e737667)](https://travis-ci.org/tivie/php-htaccess-parser) [![Latest Stable Version](https://camo.githubusercontent.com/13b6a7e31e0c8ccb72f04127718a9e2968ad140c8327e84a8704acc6eeb8538c/68747470733a2f2f706f7365722e707567782e6f72672f74697669652f68746163636573732d7061727365722f762f737461626c652e737667)](https://packagist.org/packages/tivie/htaccess-parser) [![License](https://camo.githubusercontent.com/44914a6e81243bcf1ce057f0b636e477b1138c3e6343fa0d245cc9da41ba5513/68747470733a2f2f706f7365722e707567782e6f72672f74697669652f68746163636573732d7061727365722f6c6963656e73652e737667)](https://packagist.org/packages/tivie/htaccess-parser) [![SensioLabsInsight](https://camo.githubusercontent.com/ff38b0f71ce61bb1c6f47a7a71540905a8f25734de5567b05a23c04a8a82e998/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f38626431306532632d333364352d343830302d386431392d6539626532333632656565662f6d696e692e706e67)](https://insight.sensiolabs.com/projects/8bd10e2c-33d5-4800-8d19-e9be2362eeef)

A lightweight PHP htaccess parser

Introduction
------------

[](#introduction)

PHP Htaccess Parser is a small lightweight library that can parse (or tokenize, if you prefer) an apache .htaccess file. It was developed for personal use to safely read and manipulate .htaccess files.

Features
--------

[](#features)

The parser supports:

- Directives (example: `Options -MultiViews`)
- Blocks and subBlocks (example: ``)
- Multiline statements (lines ended with `/`)
- White lines
- Comments

Installation
------------

[](#installation)

You can install it by cloning the git repository, downloading the phar archive (coming soon) or using composer.

### Git clone

[](#git-clone)

```
git clone https://github.com/tivie/php-htaccess-parser.git

```

### Composer

[](#composer)

Add these lines to your composer.json:

```
    {
        "require": {
            "tivie/htaccess-parser": "*"
        }
    }
```

or run the following command:

```
php composer.phar require tivie/htaccess-parser

```

How it works
------------

[](#how-it-works)

Each line of the file .htaccess file is parsed and then converted into one of the following tokens:

- [**WHITELINE**](https://github.com/tivie/php-htaccess-parser/blob/master/src/Token/WhiteLine.php)
- [**COMMENT**](https://github.com/tivie/php-htaccess-parser/blob/master/src/Token/Comment.php)
- [**DIRECTIVE**](https://github.com/tivie/php-htaccess-parser/blob/master/src/Token/Directive.php)
- [**BLOCK**](https://github.com/tivie/php-htaccess-parser/blob/master/src/Token/Block.php)

Each token implements [**TokenInterface**](https://github.com/tivie/php-htaccess-parser/blob/master/src/Token/TokenInterface.php) provides a simple api to read and modify its properties.

Tokens are aggregated in an [**HtaccessContainer**](https://github.com/tivie/php-htaccess-parser/blob/master/src/HtaccessContainer.php) that can be used to add, modify or remove Token objects and dumping it as plain text or json.

Quick Usage guide
-----------------

[](#quick-usage-guide)

Using PHP Htaccess Parser is very simple.

```
$file = new \SplFileObject('path/to/.htaccess');
$parser = new \Tivie\HtaccessParser\Parser();
$htaccess = $parser->parse($file);
```

You can then use `$htaccess` to manipulate .htaccess contents.

```
$block = new Block();
$htaccess[0] = $block;
```

For instance, to print the first token of the file:

```
echo $htaccess[0];
```

Casting a Token or an HtaccessContainer object to string returns a string representation of that element that can be used to recreate the .htaccess file.

```
$output = (string) $htaccess;
file_put_content('.htaccess', $htaccess);
```

Components
----------

[](#components)

### The Parser

[](#the-parser)

The [Parser class](https://github.com/tivie/php-htaccess-parser/blob/master/src/Parser.php) is the main component of the library. Since it's constructor doesn't require any mandatory argument, initializing a Parser object is very simple:

```
$parser = new \Tivie\HtaccessParser\Parser();
```

### Parser Options

[](#parser-options)

The parser's behavior can be changed through the following methods and/or options:

#### Setting the file

[](#setting-the-file)

The parser uses \\SplFileObject to access files. You can set the appropriate file in the constructor, by calling `setFile()` or as the first parameter of `$parser->parse`

```
$parser = new Parser(new \SplObjectStorage('/path/to/file'));
$parser->setFile(new \SplObjectStorage('/path/to/file'));
$parser->parse(new \SplObjectStorage('/path/to/file'));
```

#### Changing the container

[](#changing-the-container)

By default, `$parser->parse()` returns an [HtaccessContainer](https://github.com/tivie/php-htaccess-parser/blob/master/src/HtaccessContainer.php) object (which extends ArrayObject) that contains the newly tokenized .htaccess file. You can change the returned object by calling `setContainer()`method:

```
$parser->setContainer($myContainer);
```

`$myContainer` can be an array or an object that implements `ArrayAccess`.

#### Use arrays

[](#use-arrays)

Each Token is an object that implements the `TokenInterface`, which presents several useful methods. However, if you prefer, you can instruct the parser to use simple arrays instead by either:

- calling the method `useArrays()`

```
$parser->useArrays(true);
```

- using the flag `USE_ARRAYS` with the `parse` method.

```
$parser->parse(null, USE_ARRAYS);
```

#### Ignoring White and Comment Lines

[](#ignoring-white-and-comment-lines)

You can instruct the parser to ignore WhiteLines, CommentLines or both by:

- calling the respective method

```
$parser->ignoreWhiteLines(true)
       ->ignoreComments(true);
```

- or set it as a flag in `$parser->parse`

```
$parser->parse(null, IGNORE_WHITELINES|IGNORE_COMMENTS);
```

#### Rewind file

[](#rewind-file)

By default, prior to serialization, the Parser rewinds the file pointer to the beginning. You can override this by calling the `rewindFile` method.

```
$parser->rewindFile(false);
```

#### Extending the Parser

[](#extending-the-parser)

The Parser class provides API points that developers can override. For more information, you can check the code at

---

### HtaccessContainer Object

[](#htaccesscontainer-object)

The default returned object ([HtaccessContainer](https://github.com/tivie/php-htaccess-parser/blob/master/src/HtaccessContainer.php)) implements [ArrayAccess](http://php.net/manual/en/class.arrayaccess.php), so you can access the definitions as you would with an array. The keys of this array are numeric and ordered by their appearance in the original file.

#### Retrieving a Token

[](#retrieving-a-token)

Since the Parser returns an array or an array like object, you can retrieve a specific token by its index:

```
$firstToken = $htaccess[0];
```

You can also use the `search` method to find a specific token by its name:

```
$modRewrite = $htaccess->search('modRewrite');
```

You can constrain the search to a specific token type.

```
$modRewrite = $htaccess->search('modRewrite', \Tivie\HtaccessParser\Token\TOKEN_BLOCK);
```

#### Modifying a Token

[](#modifying-a-token)

[**TokenInterface**](https://github.com/tivie/php-htaccess-parser/blob/master/src/Token/TokenInterface.php) provides a common API that you can use to manipulate the tokens.

```
$token->setName('fooBar'); //Changes the name of the Token
$token->setArguments('foo', 'bar', 'baz'); //Changes the Token arguments
```

Keep in mind, however, that with some tokens, an array of arguments doesn't make much sense. For instance, [**Comments Tokens**](https://github.com/tivie/php-htaccess-parser/blob/master/src/Token/Comment.php) only expect 1 argument (the actual text of the comment) while [**WhiteLine Tokens**](https://github.com/tivie/php-htaccess-parser/blob/master/src/Token/WhiteLine.php) expect none so extra arguments will be **silently ignored**.

#### Adding a Token

[](#adding-a-token)

You can add a token by simply creating and appending it.

```
$newBlock = new Block('modRewrite');
$htaccess[] = $block;
```

You can also insert a Token into a specific index using `insertAt`:

```
$newBlock = new Block('modRewrite');
$htaccess->insertAt(4, $newBlock);
```

#### Outputting htaccess

[](#outputting-htaccess)

In order to output an .htaccess txt file, you can cast the [**HtaccessContainer**](https://github.com/tivie/php-htaccess-parser/blob/master/src/HtaccessContainer.php) to string and write the resulting string to a file:

```
$output = (string) $htaccess;
file_put_content('.htaccess', $output);
```

You can also use the method `txtSerialize` to control how the output should be formatted:

```
$output = $htaccess->ignoreWhiteLines(true)
                   ->ignoreComments(false);
file_put_content('.htaccess', $output);
```

NOTE: Keep in mind that ignored elements in the parser won't be available to HtaccessContainer serialize methods.

Contribute
----------

[](#contribute)

Feel free to contribute by forking or making suggestions.

Issue tracker:

Source code:

License
-------

[](#license)

PHP Htaccess Parser is released under Apache 2.0 license. For more information, please consult the [LICENSE](https://github.com/tivie/php-htaccess-parser/blob/master/LICENSE) file in this repository or .

###  Health Score

13

—

LowBetter than 1% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity1

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity21

Early-stage or recently created project

 Bus Factor1

Top contributor holds 80.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/3b9b873a3ab532be8b148c0da96ce9c37931a2268d52af7a00e0d0251f855088?d=identicon)[josefglatz](/maintainers/josefglatz)

---

Top Contributors

[![tivie](https://avatars.githubusercontent.com/u/1608730?v=4)](https://github.com/tivie "tivie (41 commits)")[![impopular-guy](https://avatars.githubusercontent.com/u/34854740?v=4)](https://github.com/impopular-guy "impopular-guy (3 commits)")[![josefglatz](https://avatars.githubusercontent.com/u/2861556?v=4)](https://github.com/josefglatz "josefglatz (3 commits)")[![twouters](https://avatars.githubusercontent.com/u/170895?v=4)](https://github.com/twouters "twouters (2 commits)")[![mbrodala](https://avatars.githubusercontent.com/u/5037116?v=4)](https://github.com/mbrodala "mbrodala (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")

### Embed Badge

![Health badge](/badges/josefglatz-htaccess-parser/health.svg)

```
[![Health](https://phpackages.com/badges/josefglatz-htaccess-parser/health.svg)](https://phpackages.com/packages/josefglatz-htaccess-parser)
```

###  Alternatives

[mainwp/mainwp-child

This is the Child plugin for the MainWP Dashboard

973.4k](/packages/mainwp-mainwp-child)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
