My .htaccess redirects everything to my index.php, but I wonder if it's vulnerable to XSS attacks. Am I safe?

.htaccess file

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .*$ index.php/$1 [L]
php_value auto_append_file none


require_once 'dbliteconnect.php';
$req['status'] = (php_sapi_name() == 'cli') ? "true" : 'false';
if (php_sapi_name() == 'cli' || (isset($_SERVER['argc'])) && $_SERVER['argc'] > 0)     {
$var = isset($argv[1]) ? $argv[1] : '';
$var = strreplace("/", "", $var);
$req['var'] = $var;
if (isset($_SERVER['REQUEST_URI']) && php_sapi_name() != 'cli-server') {
$var = strreplace('/'.basename(DIR_), "", $_SERVER['REQUEST_URI']);
$var = str_replace("/", "", $var);
$var = str_replace(".html", "", $var);
$req['var'] = $var;
if (php_sapi_name() == 'cli-server') {
$var = substr($var, 1);
$var = strreplace("/", "", $var);
$var = str_replace(".html", "", $var);
$req['var'] = $var;
  • 5
    \$\begingroup\$ Neither your .htaccess nor your index.php has anything to do with XSS, since the code you have shown us is not responsible for emitting any HTML output. Your application may or may not be vulnerable to XSS, but we can't tell from this excerpt. \$\endgroup\$ Commented Nov 2, 2016 at 23:58
  • 1
    \$\begingroup\$ I'm sorry, but do you even know what XSS actually means? It stands for X (cross) Site Scripting. There's nothing in this code that has anything to do with handling potential XSS vulnerabilities. A basic example would be: a form field is submitted, and the value is later used to generate HTML. If the client submits <script>window.location = 'harful url';</script> and you failed to sanitize the submitted data (or properly escape the output), you have an XSS vulnerability... \$\endgroup\$ Commented Nov 4, 2016 at 11:39
  • \$\begingroup\$ Just Read Up on php_sapi_name, Are you attempting to determine whether a user is viewing your page from the command line? \$\endgroup\$
    – Ryan Stone
    Commented Aug 17, 2019 at 15:00

2 Answers 2


The common definition of XSS is that code faults which allow someone to manipulate your website appearance, access prohibited sections of data, view inaccessible files or possibly steal credentials and cheat your app's users into entering data on the wrong website.

One of the most commonly used XSS vulnerabilities is what we call "free input" when the app allows users to insert HTML or javascript into a form which using POST or GET HTTP methods.

The reason why XSS exists is not sanitizing user free input, allowing someone to inject code into your form which can lead to injecting remote javascript which can write the data you enter into the app database and stealing your information.

A very common method to do this is for phishing purposes to steal login credentials and account information.

To prevent script injections and attempts to modify your PHP’s global and request variables, use the following in your .htaccess:

<IfModule mod_rewrite.c>
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule .* index.php [F,L]

You may use this free online XSS scanner to ensure the cleanness of your pages, http://xss-scanner.com/ and don't forget to use mod_security which would help reduce this kind of attacks.

By the way, you never trust user provided data inputs which include $_POST, $_GET, file uploads, cookies and HTTP headers (like User-Agent and Referer) such data must always be treated as untrusted and needs to be secured for each context especially if you're going to insert these inputs to your database.

Here is a very useful article including tips and tricks of .htaccess http://viralpatel.net/blogs/21-very-useful-htaccess-tips-tricks/

  • \$\begingroup\$ You have more or less answered the question, but you did not directly address the original posters code. Is there anything you can say about what is good or what can be improved in the original code? \$\endgroup\$
    – pacmaninbw
    Commented Nov 2, 2016 at 23:52
  • \$\begingroup\$ I recognize i phrased it poorly. I was more thinking in the line of adding arbitrarily query strings to the url. Does it strip those query strings. \$\endgroup\$
    – Sample_d
    Commented Nov 3, 2016 at 7:54
  • \$\begingroup\$ @pacmaninbw His code has nothing to do with XSS, it is just manipulating URIs \$\endgroup\$
    – HaniGamal
    Commented Nov 8, 2016 at 19:29

Neither you .htaccess file or your .php file would be Vulnerable to Xss Attacks as they are both server side scripts which would never be Shown to a user & therefore would not be easily manipulated.

to add a layer of protection for your site against Xss look over the following snippet.

In the .htaccess file that is in the main root directory of your website add the following module

    <IfModule mod_headers.c>
       # Make sure proxies don't deliver the wrong content
          # Header always set Content-Security-Policy: upgrade-insecure-requests        // This one can be a pain in the A** to set up, which is why I commented it out.
         Header set Strict-Transport-Security "max-age=122112887284; includeSubDomains; preload"
         Header append Vary User-Agent env=!dont-vary
         Header always append X-Frame-Options SAMEORIGIN
         Header set X-XSS-Protection "1; mode=block"       // This is the Xss header you are looking for
         Header set X-Content-Type-Options nosniff
         Header set Access-Control-Allow-Origin "*"
         IndexIgnore *.zip *.css *.js *.pyt    
         Options -MultiViews -Indexes        

    <IfModule mod_security.c>
         SecFilterEngine On
                # ^Turn the filtering engine On or Off
         SecFilterScanPOST On
                # ^Should mod_security inspect POST payloads
         SecFilterSelective "HTTP_USER_AGENT|HTTP_HOST" "^$"
                # ^Require HTTP_USER_AGENT and HTTP_HOST in all requests
         SecFilter "../"
                # ^Prevent path traversal (..) attacks
         SecFilter "<[[:space:]]*script"
                # ^Weaker XSS protection but allows common HTML tags
         SecFilter "<(.|n)+>"
                # ^Prevent XSS atacks (HTML/Javascript injection)
         SecFilter "delete[[:space:]]+from"
         SecFilter "insert[[:space:]]+into"
         SecFilter "select.+from"
         SecFilter "drop[[:space:]]table"
                # ^Very crude filters to prevent SQL injection attacks
         SecFilterSelective ARG_PHPSESSID "!^[0-9a-z]*$"
         SecFilterSelective COOKIE_PHPSESSID "!^[0-9a-z]*$"
                # ^Protecting from XSS attacks through the PHP session cookie
         SecFilterDefaultAction "deny,log,status:500"
                # ^Action to take by default
                # Block access to backup and source files.
                # These files may be left by some text editors and can pose a great security
                # danger when anyone has access to them.

    <FilesMatch "(^#.*#|.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|sw[op])|~)$">
         Order allow,deny
         Deny from all
         Satisfy All

All Subsequent Folders & directorys will inherit these rules unless otherwise specified.

The code that you have provided looks like it is from the 'www' or 'public_html' directories, Xss headers I believe should be set in the Main root directory to protect the entire web application.

you should also be using PhP PDO(Prepared statements) for any database connections & making sure to sanitize/escape any input fields. you can Add to this by researching and implementing php built in functions called htmlentities(); & pdo_real_escape_string(); Note that the mysql_real_escape_string(); function is Now deprecated and should not be used anymore.

Another thing I noticed is according to this article: htAccess-Auto Prepend & Auto Append

auto_prepend_file and auto_append_file directives do not work in the .htaccess file.

This is a very thorough article about .htaccess implementations & is well worth a read: https://www.viralpatel.net/21-very-useful-htaccess-tips-tricks/

I Found 2 Other Sources that helps prevent Xss, or add an extra layer of annoyance to any potential Hacker if combined with the other Methods.

  <meta http-equiv=”window-target” content=”_top” /> &
   <base target="_top">

The main use is to prevent a page from appearing inside another framed page: Usually this means that the Web browser will force the page to go the top frameset.
Although this Window-target meta thread on StackOverflow Suggest's That The Top one is No longer supported By Browsers Anymore

They Do provide a Javascript Fallback which is;

if (top != self) {
    top.location.href = self.location.href;

CSRF & CSP would be worth a study also.

You can also use some of these tools online to automatically scan for vulnerabilities::
Pen-Test Tools
Mozilla Observatory is Another Very good one: Hope this helps a little or Helps someone viewing it.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.