Search code examples
htmlcsscapachecgi

Link the CSS file to the HTML one in CGI programm


So, I recently started to code a web interface with CGI, after finding how to print hello world on my Apache web page with HTML, I wanted to add some CSS to it but apparently it doesn't work.

I'm on Linux, and I am working with Apache2.

So there is my source file hello.c (which is in /usr/lib/cgi-bin):

#include <stdio.h>

int main()
{
    printf(
        "Context-type:text/html\n\n"
        "<html>\n"
        "<head>\n"
        "<title> Hi world </title>\n"
        "<link type=\"text/css\" rel=\"stylesheet\" href=\"style/style.css\">\n"
        "</head>\n"
        "<body>\n"
        "<h2>Hello world !</h2>\n"
        "</body>\n"
        "</html>\n"
    );

    return 0;
}

and there is my CSS file (which is in /usr/lib/cgi-bin/style/):

body {
    background-color:rgb(255, 0, 170); 
}

h2 {
    font-family: Times;
    font-size: 38pt;
}

I already tried to put my CSS file in my home directory but it doesn't work too.


Solution

  • If you check your network panel of your browser's debugger, you're probably encountering a 500 status, as the server refuses to serve /cgi-bin/style/style.css.

    Generally, style sheets do not belong in the CGI directory. You should move them to somewhere in your DocumentRoot path.


    Assuming your configuration is something like:

    DocumentRoot "/var/www"
    ScriptAlias /cgi-bin/ "/usr/lib/cgi-bin/"
    

    Set your directory structure to:

    /usr/lib/
    └── cgi-bin
        └── hello.cgi
    /var/www
    └── style
        └── style.css
    

    Then change the relative path

    "<link type=\"text/css\" rel=\"stylesheet\" href=\"style/style.css\">\n"
    

    to an absolute path (note the / prefix):

    "<link type=\"text/css\" rel=\"stylesheet\" href=\"/style/style.css\">\n"